Sahil Lombar
Sahil Lombar

Reputation: 145

Android: CountDownTimer vs AlarmManager

I have to run a piece of code every 5 minutes in my service. Will countdowntimer be killed since the app is not in foreground. If this is the case will alarmanager be better in running the code?

Thanks, Sahil

Upvotes: 0

Views: 702

Answers (1)

Xaver Kapeller
Xaver Kapeller

Reputation: 49817

I think especially if your code runs in a Service that an AlarmManager is the better alternative. You can use the AlarmManager to start your Service in a 5 minute interval like this:

Calendar calendar = Calendar.getInstance();

Intent intent = new Intent(context, YourService.class);

// Set action of Intent or add extras

long period = 5 * 60 * 1000; // 5 minutes

PendingIntent pendingIntent = PendingIntent.getService(context, alarmId, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), period, pendingIntent);

If you want to stop your alarm you have to use the same alarmId so it would be best if you put that id in a constant. Also note that you have to restart your alarm every time the phone reboots!

Upvotes: 1

Related Questions