First create an IntentService and override onHandleIntent:
@Override
protected void onHandleIntent(Intent intent) {
updateLocationInBackground(); // or whatever task you need to do every x minutes
scheduleNextUpdate();
}
The method simply does this:
private void scheduleNextUpdate() {
new Scheduler().start();
}
Scheduler thread would look like this:
private class Scheduler extends Thread {
@Override
public void run() {
Intent i = new Intent(UserLocationUpdaterService.this, UserLocationUpdaterService.this.getClass());
PendingIntent pendingIntent = PendingIntent.getService(UserLocationUpdaterService.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
long currentTime = System.currentTimeMillis();
/* Replace this part with your computation as to when the next trigger should happen. Mine is set to fire off every 5 minutes.*/
long nextUpdateTimeMillis = currentTime + (5 * DateUtils.MINUTE_IN_MILLIS);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}
}
Fire off this Intent with startService() either on your main Activity, or on some BroadcastReceiver that has BOOT_COMPLETED registered, or both.