androidandroid-layouttimepickerandroid-timepicker

problem with alarm manager delay in alarm ringing


I have encountered a problem where when I set a time, there is a delay for the alarm to ring. Sometimes the alarm goes off early too. I am not sure where I did wrong. Hope someone can help me with this problem.

public void showHourPicker(View view) {


    currentHour = calendar.get(Calendar.HOUR_OF_DAY);
    currentMinute = calendar.get(Calendar.MINUTE);

    timePickerDialog = new TimePickerDialog(MainActivity.this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int hourOfDay, int minutes) {

            if (hourOfDay >= 12) {
                amPm = "PM";
            } else {
                amPm = "AM";
            }
            txtTime.setText(String.format("%02d:%02d ", hourOfDay, minutes) + amPm);

            calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
            calendar.set(Calendar.MINUTE,minutes);
        }

    }, currentHour, currentMinute, false);

    timePickerDialog.setTitle(" Your Expected Time : " + exp.getText());
    timePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    timePickerDialog.show();

    startAlarm(calendar);

}

public void startAlarm(Calendar calendar) {

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

}

Solution

  • This is intended behavior as described in AlarmManager.setRepeating:

    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.