views:

50

answers:

3

Hi All,

Is there a way that trough the application, I can subscribe and unsubscribe for the "ACTION_BOOT_COMPLETED" message?

If so, how can I do this?

Any kind of pointer will help me.

Thanks in advance,
Regards,
Vinay

A: 

As a matter of fact, there is:

Your boot receiver:

public class BootstrapReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context cntxt, Intent intent) {
      String action = intent.getAction();

      if(Intent.ACTION_BOOT_COMPLETED.equals(action)) {
          // do your thing
      }     
   }
}

Add a receiver and a permission for receiving boot events:

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

  <receiver android:name=".BootstrapReceiver" android:enabled="true">
     <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
  </receiver>

Via the application (Use this if you want to programatically add/remove boot receiver and not via AndroidManifest.xml. But remember, you will still have to declare the boot permission in your AndroidManifest.xml)

  Context ctx = getContext();
  BootstrapReceiver booter = new BootstrapReceiver();
  IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
  ctx.registerReceiver(booter, filter);

Unregister:

  ctx.unregisterReceiver(booter);
naikus
Your second part doesn't work. By definition BOOT_COMPLETED is only sent when the system first boots... before your app has run... so there is no opportunity to call registerReceiver() to tell it about the receiver before the broadcast is sent.
hackbod
@hackbod Its quite obvious to mention here, it will work only on next boot
naikus
No, it won't work. The registerReceiver() only lasts for the lifetime of the process. That is why there is no need to have BootstrapReceiver in your manifest -- this just sets up a direct callback to the Receiver instance you provide. Once the instance goes away (when your process goes away), the registration is gone.
hackbod
@hackbod, You are right! I checked the documentation and there seems to be no way to do that. My bad :)
naikus
Yes there is a way to do that: it's called `PackageManager.setComponentEnabledSetting`.
Christopher
A: 

The best way to do this is use PackageManager.setComponentEnabledSetting(): http://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName, int, int)

So simply decide whether you want your receiving to be enabled or not by default by setting android:enabled in the manifest. Then use this API to explicitly enable or disable the component at run time as desired. If the component is disabled, at boot it will not be available, and thus not receive the broadcast.

hackbod

related questions