Thursday, July 16, 2009

Permissions Journey: RECEIVE_BOOT_COMPLETED Tutorial

When you need your application to start when the phone had powered on, then you need to use the RECEIVE_BOOT_COMPLETED permission. On this tutorial i will use the Battery Status Application for reference.

First up, you need to add the permission on the manifest file and the receiver class
<application android:icon="@drawable/icon" android:label="@string/app_name">
  .....
  <receiver android:name=".BatteryReceiver">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
  </receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Explanation
Tell android that we have a receiver
<receiver android:name=".BatteryReceiver">

Tell android that we need to do something after the boot is completed
<action android:name="android.intent.action.BOOT_COMPLETED" />

Now tell android that we need a boot complete permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />





BatteryReceiver Class
public class BatteryReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    // do what ever you want
    PrefsActivity.connectToBatteryService(context);
  }
}



Explanation
First we need to extend our class to BroadcastReceiver to receive an instruction
public class BatteryReceiver extends BroadcastReceive

Then the magic takes place at onReceive function, on my app i just enable the BatteryService class
// do what ever you want

Hope this helps

Update History
   Jan 17, 2012 - Visual Update
Post a Comment