6

How can I execute an action (maybe an Intent) on every specified time (e.g. Every day on 5AM)? It has to stay after device reboots, similar to how cron works.

I am not sure if I can use AlarmManager for this, or can I?

Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228

2 Answers2

10

If you want it to stay after the device reboots, you have to schedule the alarm after the device reboots.

You will need to have the RECEIVE_BOOT_COMPLETED permission in your AndroidManifest.xml

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

A BroadcastReceiver is needed as well to capture the intent ACTION_BOOT_COMPLETED

<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Lastly, override the onReceive method in your BroadcastReceiver.

public class BootcompletedReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
     //set alarm
  }
}

Edit: Look at the setRepeating method of AlarmManager to schedule the 'Android cron'.

SteD
  • 13,909
  • 12
  • 65
  • 76
  • That will not help you in case your application is killed by the user or the Android system. Once it does, your alarms get unregistered, and you will never get called again. – Guy Dec 17 '12 at 20:13
  • I couldn't find anything about set repeating via cron expression! – Dr.jacky May 11 '15 at 12:12
1

Using the BuzzBox SDK you can schedule a cron job in your App doing:

SchedulerManager.getInstance()
.saveTask(context, "0 8-19 * * 1,2,3,4,5", YourTask.class);

Where "0 8-19 * * 1,2,3,4,5" is a cron string that will run your Task once an hour, from 8am to 7pm, mon to fri. You Task can be whatever you want, you just need to implement a doWork method. The library will take care of rescheduling on reboot, of acquiring the wake lock and on retrying on errors.

More info about the BuzzBox SDK here...

robsf
  • 1,713
  • 3
  • 14
  • 26