[英]Check whether onPause state of activity is called due to screen lock
如果我的应用程序正在运行并且按了锁定屏幕按钮,它将把应用程序置于后台。检查屏幕锁定是否调用onPause()的方法是什么?
All you have to do is check if the screen is on or not. 您要做的就是检查屏幕是否打开。
@Override
protected void onPause() {
super.onPause();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean screenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
screenOn = pm.isInteractive();
} else {
screenOn = pm.isScreenOn();
}
if (screenOn) {
// Screen is still on, so do your thing here
}
}
You Can Simply Know It By Using This Method 您可以使用此方法简单地知道它
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
System.out.println("On Pause called");
}
For Keeping The Device Awake while lock screen. 用于在锁定屏幕时保持设备唤醒。 Documentation.
文档。
Ok in your case you would need Wake_Lock
好了,您需要
Wake_Lock
To use a wake lock, the first step is to add the WAKE_LOCK permission to your application's manifest file:
要使用唤醒锁,第一步是将WAKE_LOCK权限添加到应用程序的清单文件中:
<uses-permission android:name="android.permission.WAKE_LOCK" />
If your app includes a broadcast receiver that uses a service to do some work, you can manage your wake lock through a WakefulBroadcastReceiver , as described in Using a WakefulBroadcastReceiver.
如果您的应用程序包括使用服务执行某些工作的广播接收器,则可以通过使用WakefulBroadcastReceiver来管理唤醒锁,如使用WakefulBroadcastReceiver中所述。 This is the preferred approach.
这是首选方法。 If your app doesn't follow that pattern, here is how you set a wake lock directly:
如果您的应用程序不遵循该模式,则可以通过以下方法直接设置唤醒锁:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); Wakelock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag"); wakeLock.acquire();
To release the wake lock, call wakelock.release().
要释放唤醒锁,请调用akelock.release()。 This releases your claim to the CPU.
这将使您向CPU提出索赔。 It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.
请务必在应用程序使用完后立即释放唤醒锁,以免耗尽电池。
DO this after setting powermanager. 设置电源管理器后执行此操作。
boolean screenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
screenOn = powerManager.isInteractive();
} else {
screenOn = powerManager.isScreenOn();
}
if (screenOn) {
// Screen is still on, so do your thing here
}
You just want to know when onPause is called? 您只想知道何时调用onPause? You could override the super function and add logging to the function:
您可以覆盖超级功能并将日志添加到该功能:
@Override
public void onPause() {
super.onPause();
System.out.println("On Pause called");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.