I want run some piece of code every day arond at 8 a.m. I have this code in onCreate in MainActivity
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, PriceAmountService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);
But this run the job every time when app is started. Is my code good or wrong? Is this code on right place (onCreate)? What I do wrong?
My min API is 14
Thanks to Doug Stevenson I solve this problem by adding simple if to my method. My method for raise some job exactly at 8:00am is:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
if (Calendar.getInstance().after(cal)) {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(this, PriceAmountService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pintent);