Search code examples
javaandroidalarmmanager

Why alarm fire always when i close activity


In Android studio i want my application send notification to user if he do no use it. Notification is fire but always when i leave the activity and after 8:00

@Override
protected void onStop() {
    super.onStop();
    System.out.println("STARTED!");
    Intent intent = new Intent(this, Alarm.class);
    PendingIntent pendingIntent = 
    PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 1);
    alarmManager.cancel(pendingIntent);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}

The alarm fires once always when i leave the activity and the time is greater then 8:00;


Solution

  • Because it is not exact.

    Documentation says "Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact."

    https://developer.android.com/training/scheduling/alarms

    If you want to be precise about the time you must change your

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

    method. You should consider using not repeating alarms(alarmManager.setExact method). If you still want to schedule repeating alarm, you can reschedule it in Alarm on receive method.