Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to receive a notification when the user powers off the device?

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?

like image 582
BenIOs Avatar asked Feb 03 '10 06:02

BenIOs


1 Answers

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.

like image 57
Dave Webb Avatar answered Sep 19 '22 20:09

Dave Webb