Kim Vu Kim Vu - 1 month ago 9
Java Question

My service is started immediately in my alarmmanager

This Method is in MyClass.java that extends Service

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
settPeriodicService = this;
HOUR = 0;
MINUTE = 0;
message="Happy birthday!";
if(running) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,HOUR);
calendar.set(Calendar.MINUTE,MINUTE);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.DAY_OF_YEAR,1);
Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
running = true;
}
return super.onStartCommand(intent, flags, startId);
}


Why does MyService start immediately?

Answer
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,HOUR);
calendar.set(Calendar.MINUTE,MINUTE);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.DAY_OF_YEAR,1);

Above calendar represents a time in the past because you set the day to january 1st with calendar.set(Calendar.DAY_OF_YEAR,1);. Setting a time in the past will trigger the alarm immediately.

You probably want to do this:

calendar.add(Calendar.DAY_OF_YEAR,1);

to set the calendar to tomorrow.

Comments