android – Turning on screen programmatically-ThrowExceptions

Exception or error:

I would like to unlock screen and switching it on to show a popup on an event trigger. I am able to unlock the screen using

newKeyguardLock = km.newKeyguardLock(HANDSFREE);
newKeyguardLock.disableKeyguard();

on KeyGuardService but I cannot turn on the screen. I am using

wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, HANDSFREE);
wl.acquire();

but with no success. The screen still remains off.
How can I achieve this?

How to solve:

Note from author: I wrote this back in 2012. I don’t know if it works anymore. Be sure to check out the other more recent answers.


Amir’s answer got me close, but you need the ACQUIRE_CAUSES_WAKEUP flag at least (Building against Android 2.3.3).

WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
     PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();

//later
screenLock.release();

###

This is very popular question but the accepted answer now is outdated.

Below is latest way to Turn On Screen OR wake up your device 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 WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON but FLAG_TURN_SCREEN_ON flag has been deprecated in API level 27 so you can use Activity.setTurnScreenOn(true) from API level 27 onward.

###

In your main activity’s OnCreate() write following code:

((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG").acquire();

It causes the device to wake up.

Do not forget disableKeyguard() to unlock the device…

###

undefined’s answer with NullPointer check and set timeout :

private void turnOnScreen() {
    PowerManager.WakeLock screenLock = null;
    if ((getSystemService(POWER_SERVICE)) != null) {
        screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        screenLock.acquire(10*60*1000L /*10 minutes*/);


        screenLock.release();
    }
}

###

I have the same issue. As these guys discussed here, there is a hidden api to turn screen on/off, see: https://android.googlesource.com/platform/frameworks/base/+/froyo-release/core/java/android/os/Power.java

But I don’t know how to call it. I have actually seen a application can turn screen on, wondering if it is device specific.

Leave a Reply

Your email address will not be published. Required fields are marked *