I need to create a BroadcastReceiver which performs certain task immediately each time the device boots up. Also, when a certain button is clicked, the receiver should stop starting on boot. Can someone help me to manage that?
-
What have you tried? There are lots of questions on this, e.g.: http://stackoverflow.com/questions/2784441/trying-to-start-a-service-on-boot-on-android – qzikl Dec 19 '12 at 19:16
-
issue is to stop BroadcastReceiver when certain button is clicked. this certain button is in your application or any other? – ρяσѕρєя K Dec 19 '12 at 19:18
-
my app only. Thanks guys, Ralgha's solution seems to work – Droidman Dec 19 '12 at 20:52
1 Answers
All you need to solve the first part of your question is to make a BroadcastReceiver for it and declare it in your Manifest as:
<receiver android:name=".MyBootReceiver"
android:enabled="true"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
The QUICKBOOT_POWERON is necessary for some devices that don't send the BOOT_COMPLETED broadcast. HTC devices like to use the quickboot one instead.
For the second part of your question, there are a few different ways you could accomplish this. You could simply set a value in SharedPreferences that your receiver checks every time it fires, and exit immediately if the value dictates such.
You could also disable the receiver in code:
getPackageManager().setComponentEnabledSetting(
new ComponentName( this, MyBootReceiver.class ),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP );
You can enable it using the same method:
getPackageManager().setComponentEnabledSetting(
new ComponentName( this, MyBootReceiver.class ),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP );
I am unsure of the persistence of this method. I use it in one of my apps, but it's not for a boot receiver, and it doesn't have to persist across boots. You'll have to experiment with it if you want to go that route.
- 8,156
- 4
- 37
- 60