Question

I need to know when the user powers off his/her phone. Are there any broadcasts (or similar) that notify when the user's phone is powered off?

Was it helpful?

Solution

You can use the ACTION_SHUTDOWN Intent which is broadcast when the phone is about to shutdown. The documentation says:

Apps will not normally need to handle this, since the foreground activity will be paused as well.

In other words, if you respond to all the lifecycle events for your Activity appropriately, there's no need to use this unless you really want to do something specific related to shutdown.

The ACTION_SHUTDOWN Intent was introduced in API Level 4, in other words it'll only be sent on phones running Android 1.6 or later.

You'll trap the Broadcast with a BroadcastReceiver. It will look something like this:

public class ShutdownReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //Insert code here
    }

}

You'll also need an entry in your Manifest like the following:

<receiver android:name=".ShutdownReceiver">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
  </intent-filter>
</receiver>

Depending on what you're doing, another option would be to use the ACTION_BOOT_COMPLETED Intent which is sent when the phone is restarted.

OTHER TIPS

In addition to ACTION_SHUTDOWN, you should add android.intent.action.QUICKBOOT_POWEROFF to your intent-filter.
ACTION_SHUTDOWN isn't always broadcast on some HTC devices (e.g. the Evo 4g).
To be more specific, if you choose Restart, ACTION_SHUTDOWN is broadcast, but if you choose Power Off, QUICKBOOT_POWEROFF is broadcast instead.

To expand on what Dave Webb said is the appropriate way to handle this:

You can override the Android Activity Lifecycle functions:

protected void onPause();
protected void onResume();

In most scenarios implementing these should be sufficient and will not require you to specifically handle the "power off" events.

There's plenty more information on the Android Website and in the answer to this lifecycle question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top