Search code examples
androidalarmmanagerinfinite-loop

Android alarmManager gets into loop


I have a service, which I want to run each day so check some stuff in my db, and if needed create a notification. To run my service each day, I used an alarmManager, which works fine for the first time, but as soon as in starts my services gets in an infinite loop, I know this is because of the alarmManager since it just gets in the loop when the alarmmanager is starting. here is the code of my service:

public class MyService extends Service {

...
    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {



        checkMechanicUseer();

        this.stopSelf();


        return START_NOT_STICKY;
    }

    private void checkMechanicUseer() {

    ...

    }




    @Override
    public void onDestroy() {
        super.onDestroy();



        final SharedPreferences settings = getSharedPreferences("MYSETTINGS",0);
        int time = settings.getInt("time",9);



        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();

        calSet.set(Calendar.HOUR_OF_DAY, 9); 
        calSet.set(Calendar.MINUTE, 0);
        calSet.set(Calendar.SECOND, 0);
        calSet.set(Calendar.MILLISECOND, 0); // I want it to trigger at 09:00 am each day

        AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarm.setRepeating(
                alarm.RTC_WAKEUP,
                calSet.getTimeInMillis() ,(1000 * 60 ),
                PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
        ); // I set the (1000 * 60 ) so I can check it with 1 min interval, so I wont need to wait one day for it ... of course I need to change it to (1000 * 60 * 60 * 24)

        Toast.makeText(MyService.this, "Service destroyed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }



}

I guess I need to cancel my alarm some where, and then set another one. but have no idea how or where to do it

Still have the problem if I change the alarm.setRepeat with alarm.set as follow:

 alarm.set(
                alarm.RTC_WAKEUP,
                calSet.getTimeInMillis() + (1000 * 60 ),
                PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
        );

Solution

  • I think that it is because you set the alarm for a past date, first fire at 9 o'clock then you reset the alarm for 9 o'clock but this time is in the past so the alarm is fire immediatly and you have a nice loop.

    Check if the time is not in the past, if it is, add a day to your calendar.