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?
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
Code
PowerManager powerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "appname::WakeLock");
//acquire will turn on the display
wakeLock.acquire();
//release will release the lock from CPU, in case of that, screen will go back to sleep mode in defined time bt device settings
wakeLock.release();
in the Manifest file, the permission should be
<uses-permission android:name="android.permission.WAKE_LOCK"/>
Here is the latest way to Turn On Screen from an activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
this.setTurnScreenOn(true);
} else {
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Use FLAG_TURN_SCREEN_ON but this flag has been deprecated in API level 27 so use Activity.setTurnScreenOn(true) from API level 27 onwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With