Question

I need my app to execute a method each x minutes. But x can be different each time: It can change between 15 and 60 depending on other factors.

The method has to be executed even if the user has closed the app or even if the user has restarted the phone.

I am trying with the AlarmManager but I don't know if is the best way for my case. Is it? Or is AlarmManager a resource consuming way?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top