androidwakelock

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


I am aquireing a wakelock like this:

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

This worked for all devices I have used so far:

It did not work for:

So, it seems like, for some reason, this does not work for API level 22.

But according t the documentation of FLAG_KEEP_SCREEN_ON, it has been there since API 1 and therefor should be usable anywhere.

StackTrace:

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.access$800(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)

Why does this only seem to happen at API 22 and how do I fix this issue?


Solution

  • I solved this very simply. I didn't use PowerManager, Wakelock or anything:

    android:keepScreenOn="true"
    

    Add this line to your activity layout. Obviously this only works when the activity, as in my case, is supposed to always stay on.