Saturday, April 20, 2013

Android Tip - Waking up screen and unlocking the device

In Android, there are times where you need to programmatically unlock the device and wake up the screen. For example, you might have a broadcast receiver that receives some broadcasts in the background. When a broadcast is received, you want to wake up the screen (which is likely to be off as the device goes to sleep) and display a notification to the user. In addition, if your device is locked, you would also need to programmatically unlock it. The following code snippet will unlock your device and wake up the screen:


import android.view.Window;
import android.view.WindowManager.LayoutParams;

...

        Window window = this.getWindow();
        window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);

Give it a try and have fun!

No comments: