"Must specify a valid wake lock level" 仅在 Pixel 2 XL 上抛出(API 22)

"Must specify a valid wake lock level" thrown only on Pixel 2 XL (API 22)

我正在获取这样的唤醒锁:

PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WAKELOCK_TAG);
mWakeLock.acquire(WAKELOCK_TIMEOUT);

这适用于我目前使用的所有设备:

它不适用于:

因此,出于某种原因,这似乎不适用于 API 级别 22。

但是根据 FLAG_KEEP_SCREEN_ON 的文档,它自 API 1 以来就已经存在,因此应该可以在任何地方使用。

堆栈跟踪:

02-27 12:13:50.775 6158-6158/com.myProject.lite E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.myProject.lite, PID: 6158
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myProject.lite/com.myProject.lite.myActivity}: java.lang.IllegalArgumentException: Must specify a valid wake lock level.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access0(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.IllegalArgumentException: Must specify a valid wake lock level.
        at android.os.PowerManager.validateWakeLockParameters(PowerManager.java:494)
        at android.os.PowerManager.newWakeLock(PowerManager.java:479)
        at com.myProject.lite.myActivity.onCreate(myActivity.java:103)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)

为什么这似乎只发生在 API 22,我该如何解决这个问题?

出于某种原因,Android API < 23 仍将 WindowManager.LayoutParams.FLAG_KEEP_SCREEN 视为无效的唤醒锁定级别。因此,您可以尝试以下操作:

PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if(Build.VERSION.SDK_INT >= 23) {
    mWakeLock = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WAKELOCK_TAG);
} else {
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKELOCK_TAG);
}

我很简单地解决了这个问题。我没有使用 PowerManager、Wakelock 或任何东西:

android:keepScreenOn="true"

将此行添加到您的 activity 布局中。显然,这仅在 activity 应该始终保持打开状态时才有效。