I need my Service to do tasks every night at 02:00, and if failed in task then schedule itself to start again after 30min, but if succeeded then stop itself and start again the other night at 02:00. I managed to get it start at 02:00 but after it is triggered it just triggeres itself continiously.
My code is in Service, and here is the code itself:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
//doTasks();
MediaPlayer player = MediaPlayer.create(this,
Settings.System.DEFAULT_NOTIFICATION_URI);
player.start();
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 2);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
doTasks() is the tasks I need to run but because they are slow I use notification sound for testing purposes. And pendingIntent is this Service itself.
Any ideas what is it that makes my AlarmManager trigger constantly?
If your
pendingIntentis set to start theServicethen basically you’re repeatedly creating a new alarm each time in theonStart(...)method.AlarmManagerhas a mechanism where it will trigger an alarm “late” if the device was asleep when it should have triggered. In your case, because you constantly re-create the alarm,AlarmManagerconstantly thinks it should be triggered immediately even if the time is past 02:00:00.Create the alarm somewhere else to prevent it being constantly re-created each time the
Servicestarts.