android – An alternative to PowerManager.FULL_WAKE_LOCK

Question:

When the push arrives, I show the notification, and I need to turn on the screen for a couple of seconds.

I use the following code in the service:

    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    if(!pm.isScreenOn())
    {
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE
                , "MyLock");
        wl.acquire(5000);
    }

The problem is that PowerManager.FULL_WAKE_LOCK marked as deprecated and it is advised to use WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON . Like this:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

But how can I access the window from the service? Moreover, the device is asleep.
Is there an alternative to FULL_WAKE_LOCK ?

Answer:

Create a transparent activity and call it from the service with the FLAG_ACTIVITY_NEW_TASK flag:

Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

In the onCreate () of the activity, use the following flags:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

After unlocking the screen, close the activity.

Scroll to Top