Running code on phone boot


SDK Version: 
M3

Some applications, for example a mail client, needs to run in the background all the time. You may want to run code right after the device booted.


The device is booting

In the Android system BroadcastReaceivers are just for such mechanism, they can listen for defined intents with given parameters, and run code when they receive one, even when your application is not running at the moment. You can define own actions and fire the manually to control your receivers, but there are a lot of predefined broadcast in the system that are fired automatically on certain events.
One of the is the BOOT_COMPLETED action. The complete list is available here.

All you need to do is a class that extends Broadcastreceiver:

  1. public class HelloReceiver extends BroadcastReceiver {
  2.   @Override
  3.   public void onReceive(Context context, Intent arg1) {
  4.     //code inserted here will run at phone boot
  5.     //you may start a Service
  6.     //or an AlarmManager to run code later too
  7.   }
  8. }

Then register it in the AndroidManifest.xml:

  1. <receiver android:name="HelloReceiver">
  2.   <intent-filter>
  3.     <action android:name="android.intent.action.BOOT_COMPLETED" />
  4.     <category android:name="android.intent.category.HOME" />
  5.   </intent-filter>
  6. </receiver>

The BOOT_COMPLETED broadcast needs a permission to use, so don't forget to add this too:

  1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>