Turn ON Screen programmatically on Android

sherpya picture sherpya · May 7, 2015 · Viewed 17.3k times · Source

I need to programmatically turn the screen on when the user turns off with power button, and yes I always have the correct flags in the Activity to keep screen on, but it does not avoid user pressing power button.

So far I've found a solution but it uses a deprecated wakelock

sWakeLock = sPM.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, TAG_WAKELOCK);

sWakeLock.acquire();
sWakeLock.release();

There is a better way to achieve it?

Answer

rubmz picture rubmz · May 7, 2015

In Lollipop you might want to add some more flags:

final Window win = getWindow();
    win.addFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON );

I got this from the AOSP https://android.googlesource.com/platform/packages/apps/DeskClock/+/dfd1960/src/com/android/deskclock/alarms/AlarmActivity.java