如何防止在屏幕锁定时调用 onStop()

How to prevent call to onStop() on screen lock

我的应用程序具有我在 onStop() 方法中调用的某些功能,即当我在应用程序之间切换时。

它有一个 videoview 所以我只想在切换应用程序时将它切换为音频。

我已经在 onStop() 方法中实现了这个,但是当屏幕被锁定时它会调用 onStop() 并且我的应用程序开始后台音频播放。

我想在屏幕锁定时保留activity而不切换到背景音频播放。

我尝试使用 broadcast receiver 来捕获屏幕锁定事件,但它在调用 onStop() 之后捕获了事件。

我需要帮助以防止在屏幕锁定时调用 onStop() 或以任何方式在调用 [=10] 之前检测屏幕锁定事件=] 方法.

首先,您不能阻止在屏幕锁定时调用onStop。当 Activity 从可见状态变为不可见状态时,它将始终被调用。

是的,您可以检测锁屏:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
  if( myKM.inKeyguardRestrictedInputMode()) {
      //it is locked
  } else {
    //it is not locked
  }

如果在设置 -> 安全 -> 屏幕锁定中将屏幕锁定设置为 none,这将不起作用。

编辑 1: 如果你想使用 PowerManager:

PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
if (pm.isInteractive()) {
   // the device is in an interactive state.
}

编辑 2:

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 Off.
}

您可以在onStop中检查屏幕是否关闭。如果开启,直接切换到音频,否则什么也不做(但不要忘记调用 onStop 的 super)。

@Override
public void onStop() {
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (pm.isScreenOn()) {
       // switch to audio
    }
    super.onStop();
}