Android Power State Change

I forgot if I did this before or if it worked before. I add these two intent filters to AndroidManifest.xml

Intent.ACTION_SCREEN_ON
Intent.ACTION_SCREEN_OFF

but it wouldn’t work. That’s super weird. Cause that’s a very basic and simple setting. After searching a little while, I realize that’s PowerManager setting. Check the Notifier.java here.

mHandler = new NotifierHandler(looper);
mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
mScreenOnIntent.addFlags(
                Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
mScreenOffIntent.addFlags(
                Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenBrightnessBoostIntent =
                new Intent(PowerManager.ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED);
mScreenBrightnessBoostIntent.addFlags(
                Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);

You can see the detail here. Android framework uses these two flags – FLAG_RECEIVER_REGISTERED_ONLY/FLAG_RECEIVER_FOREGROUND to limit which way that Apps can receive these intents.

Why Android want to do this? cause this is for security purpose. Think about that: once a virus in your phone, it might wanna restart immediately or does something in the background when your phone is on. Via these flags, you need to program that setting in your code instead of in your AndroidManifest.xml.

In that way(register in code), your App will have that ability to receive related intents and do something you wanna do.

Then, how do we make sure we can receive a notification when the phone is on, I mean, unlock and enter into launcher? Try this intent: ACTION_USER_PRESENT. And this intent can be added into AndroidManifest.xml. So, you definitely can receive that from system.

Happy codeing.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s