Start AlarmManager if device is rebooted

Cilenco picture Cilenco · Jul 16, 2013 · Viewed 13.7k times · Source

In my app I want to run some code every day at a specific time using an AlarmManager. In the android documentation I found this:

Registered alarms are retained while the device is asleep [...] but will be cleared if it is turned off and rebooted.

And that is the problem. I want to run the code even if the user reboots the phone. If the user reboots the phone he currently has to relaunch my app to start alarms again. How can I prevent this? Is there a better mechanism I should use instead?

Answer

The Holy Coder picture The Holy Coder · Jul 16, 2013

Create Boot Receiver using following code :

public class BootBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context pContext, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            // Do your work related to alarm manager
        }
    }
}

In your Manifest, register this Broadcast receiver :

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

And don't forget to add permission in AndroidManifest.xml :

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