Is there any way to receive a notification when the user powers off the device?
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.
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.