如何检测屏幕已经在Android设备上?

时间:2014-08-13 06:13:07

标签: android android-intent android-broadcast

我使用广播接收器来检测SCREEN_ON和SCREEN_OFF。只有那个时候我才能获得价值观。 但我想检测用户SCREEN在设备上打开多长时间?

有些人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我们可以使用广播Intent.ACTION_SCREEN_OFFIntent.ACTION_SCREEN_ON来检查屏幕是开还是关。

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // DO WHATEVER YOU NEED TO DO HERE
            // You can use Timer here to grab Time
            wasScreenOn = false;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // AND DO WHATEVER YOU NEED TO DO HERE
            // You can use Timer here to grab Time
            wasScreenOn = true;
        }
    }

}

答案 1 :(得分:1)

下面给出的代码会对您有所帮助。

public class myReceiver extends BroadcastReceiver {

public static boolean screenStatus = true;

private Date date1;

private Date date2;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        date2 = new Date();

        long difference = date2.getTime() - date1.getTime();
        //screen on for *difference* milliseconds 
        screenStatus = false;

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        date1 = new Date();
        screenStatus = true;
    }
}

}