Reputation: 24308
I would like to have a service run on bootup and then scheduled to run every 10 minutes. How can I go about this?
If on boot-up can I force a schedule for 10 minutes, but I presume I would need to schedule this every time on boot-up because after a reboot all schedules are lost?
Upvotes: 1
Views: 1087
Reputation: 234795
There's a nice little tutorial here that explains how to start a service at boot time that just keeps running and at some regular interval does something (writes to a log file, in the case of the tutorial).
As @CommonsWare points out, this creates an unnecessary load on the system. A better approach is to schedule a repeating alarm with AlarmManager, as described in this thread. You can register your app to receive the BOOT_COMPLETED broadcast (as described in the above tutorial) and in response schedule the alarm.
Upvotes: 1
Reputation: 3354
in my application I've registered a broadcast receiver on the ACTION_BOOT_COMPLETED Intent to be notified when the device boot has been completed. To achieve the result you have to specify in your manifest file the following:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<receiver
android:name=".YOUR_BROADCAST_RECEIVER">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
In the BroadcastReceiver I started the service with
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, serviceClass));
...
}
Finally in the onStartCommand of the service
public int onStartCommand(Intent intent, int flags, int startId) {
...
setNextSchedule();
...
}
private void setNextSchedule() {
long time = WHEN_YOU WANT_THE SERVICE TO BE SCHEDULED AGAIN;
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(this, 0,new Intent(this, this.getClass()), PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, time, pi);
}
The AlarmManger will use the pending intent to send to your service the intent you passed. Have a look here
bye
Upvotes: 0