Start AlarmManager if device is rebooted
You will need to add a boot receiver in your manifest like this
<application ... >
<receiver android:name=".OnBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</intent-filter>
</receiver>
</application>
And then create the boot receiver class like this...
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctxt, Intent intent) {
AlarmHelper.setAlarm(ctxt);
}
}
My alarm helper class is a simple start of day alarm like this...
public class AlarmHelper {
public static void testAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.SECOND, 10);
setAlarm(context, when);
}
public static void setAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.DAY_OF_YEAR, 1);
when.set(Calendar.HOUR_OF_DAY, 0);
when.set(Calendar.MINUTE, 0);
when.set(Calendar.SECOND, 0);
setAlarm(context, when);
}
@SuppressLint("SimpleDateFormat")
private static void setAlarm(Context context, Calendar when) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
Boolean showNotifications = prefs.getBoolean("PREF_SHOW_NOTIFICATIONS",
false);
if (showNotifications) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntent(context.getApplicationContext()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Log.i(TAG, "Alarm set " + sdf.format(when.getTime()));
}
}
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" />
Use can u create service using broadcast reciever on device boot up
<receiver android:enabled="true" android:name=".YourReceiver"
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />