简体   繁体   English

我如何检测Android设备屏幕即将超时或“锁定”?

[英]How do i detect when android device screen is about to timeout or “Lock”?

I have an android application that needs to detect when the screen is going to lock. 我有一个Android应用程序,需要检测屏幕何时锁定。
is it possible to discover how long the screen will stay "UnLocked" for? 是否有可能发现屏幕将保持多长时间“UnLocked”?

You will need to register a broadcast reciever.Your system will send a brodcast when device is going to sleep. 您需要注册一个广播接收器。您的系统将在设备进入睡眠状态时发送一个brodcast。 Put the following code wherever desired: 在需要的地方放置以下代码:

private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(final Context context, final Intent intent) {
  //check if the broadcast is our desired one
  if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
//here define your method to be executed when screen is going to sleep

}};

you will need to register your receiver: 你需要注册你的接收者:

    IntentFilter regFilter = new IntentFilter();
// get device sleep evernt
regFilter .addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiver, regFilter );

ACTION_SCREEN_OFF is sent after the screen turns off and ACTION_SCREEN_ON is sent after the screen turns on. ACTION_SCREEN_OFF屏幕关闭后,发送和ACTION_SCREEN_ON屏幕打开后发送。

UPDATE: 更新:

1.Method 1: As far as i know, you can not setup a listener before ur device goes to sleep.There is no such listener inside PowerManager. 1.方法1:据我所知,你不能在你的设备进入睡眠状态之前设置一个监听器。在PowerManager中没有这样的监听器。 A solution which comes to my mind is to get the device time out from the settings and then setup a count down timer in your app. 我想到的解决方案是让设备在设置中超时 ,然后在您的应用中设置倒计时器。 The countdown should be reset every time user touches screen. 每次用户触摸屏幕时都应重置倒计时。 This way you may guess the time when the device goes to sleep and then setup a wakelock before the device goes to sleep and run your desired code and after that,disable the wakelock and the put the device to sleep. 通过这种方式,您可以猜测设备进入休眠状态的时间,然后在设备进入休眠状态之前设置唤醒锁并运行所需的代码,然后禁用唤醒锁并使设备进入休眠状态。

2.Method 2: inPause() method of your activity is called when your device goes to sleep. 2.方法2:当你的设备进入睡眠状态时,会调用你的活动的inPause()方法。 You might be able to do some code there.Just a thought. 你或许可以在那里做一些代码。只是一个想法。

You have to use "Wakelock".. try this code 你必须使用“Wakelock”..试试这个代码

PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
     wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "whatever");wl.acquire();

And don't forget to take permission in your menifest "android.permission.WAKE_LOCK" and write wl.release() in your pouse() method.. 并且不要忘记在您的清单“android.permission.WAKE_LOCK”中获取权限并在您的pouse()方法中编写wl.release()。

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

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