Start AlarmManager if device is rebooted

14,071

Solution 1

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" />

Solution 2

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" />

Solution 3

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()));
}
}
Share:
14,071

Related videos on Youtube

Cilenco
Author by

Cilenco

Student at the university of Münster (Germany). I concentrate on Android development and efficient algorithms and data structures.

Updated on December 10, 2020

Comments

  • Cilenco
    Cilenco over 3 years

    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?

    • Athul Harikumar
      Athul Harikumar almost 11 years
      create a reciver for boot complete and set the alarm manager (clear if any previous alarms are there for your app too)
    • Poovizhirajan N
      Poovizhirajan N almost 11 years
    • ivanleoncz
      ivanleoncz over 7 years
      Very useful question.
  • UKDataGeek
    UKDataGeek over 10 years
    Make sure you put the uses permission (<uses-permission android:name="android.permission.WAKE_LOCK" />) into correct place in the manifest file. ( usually before activity)
  • Marija
    Marija about 5 years
    The onReceive() method does not appear to call getAction to ensure that the received Intent's action string matches the expected value, potentially making it possible for another actor to send a spoofed intent with no action string or a different action string and cause undesired behavior. So you should add this line of code in your onReceive(): if (intent.getAction().equals("android.intent.action.BOOT_COMPL‌​ETED")) { // do your work here }
  • DaveTheMinion
    DaveTheMinion about 3 years
    Do both receivers need to be defined in the AndroidManifest?