简体   繁体   English

如何检测屏幕是否已在Android设备上打开?

[英]How to detect is screen is already on, on android device?

I am using broad cast receiver to detect when SCREEN_ON and SCREEN_OFF. 我正在使用广泛的演员表接收器来检测何时SCREEN_ON和SCREEN_OFF。 Only that time i am getting the values. 只有那时,我才能获得价值。 But i want to detect how much time user SCREEN WAS ON on the device? 但是我想检测用户屏幕在设备上打开了多少时间?

Could some plz help me out on this? 可以请我帮忙吗?

we can use Broadcast for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON to check whether Screen is ON or OFF. 我们可以将Broadcast用于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;
        }
    }

}

The code given below will help you. 下面给出的代码将为您提供帮助。

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;
    }
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM