Turning on screen from receiver/service

RuAware picture RuAware · May 14, 2015 · Viewed 16k times · Source

I would like my app to be able to turn the screen on and display my app. Let's say I'm setting an alarm and every hour I want my app to be displayed for 2 mins before the device naturally sleeps.

I see that WakeLock (FULL_LOCK) and KeyguardManager are deprecated.

I have created a WakefulBroadcastReceiver and service and these are working.

@Override
protected void onHandleIntent(Intent intent) {
    // I need to show the screen here!

    for (int i=0; i<5; i++) {
        Log.i("SimpleWakefulReceiver", "Running service " + (i + 1)
                + "/5 @ " + SystemClock.elapsedRealtime());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
    }
    Log.i("SimpleWakefulReceiver", "Completed service @ " + 
          SystemClock.elapsedRealtime());
    SimpleWakefulReceiver.completeWakefulIntent(intent);
}

How do I programmatically turn on the screen, get past lock and display my Activity from the IntentService ?

Thanks

Answer

Kartheek picture Kartheek · May 21, 2015

You can use this code to turn the screen on.

lock = ((KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE);
powerManager = ((PowerManager) getSystemService(Context.POWER_SERVICE));
wake = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");

lock.disableKeyguard();
wake.acquire();
           getWindow().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);

You need the following permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

EDIT (USE THIS ONE, NOTHING IS DEPRECATED):
There is an one more alternative for doing this, for that you need to launch an activity, In the activity onCreate() you need to add the flags to the window. For example:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
      getWindow().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);`
}