Is there an accurate repeating-alarm system for An

2019-04-12 14:30发布

问题:

Background


I'm currently developing an application for Android which revolves around an alarm that goes of on an user specified time. My intent for it is that it will be used for waking people up in the morning (and the following morning - aka repeating alarm). When the alarm goes of it will call an Activity that has a couple of options (such as snooze). I've got all of this working but I'm running in to a problem.


Problem


I'm using AlarmManager to handle my alarm needs. There is however something curious going on with the class (in my opinion). There are two adviced ways to handle the setting of the alarm time. Namely setInexactRepeating and setRepeating. The problem with these functions are:

  • setInexactRepeating is not very accurate. My tests have shown that this gets approximately activated at the specified time, which the documentation indicates, all be it rather vaguely;

    the alarm will not fire before this time, but there may be a delay of almost an entire alarm interval before the first invocation of the alarm.

    My tests show there is usually something of a 5 minute delay. On this answer the user has an average delay of approximately 12 minutes. This won't do, of course, for a system that is supposed to wake people up at their specified times.

  • setRepeating does trigger at the specified time. The docs specify however that as of API 19 that all repeating alarms are inexact. Which is exactly what I don't want.

    As of API 19, all repeating alarms are inexact. Because this method has been available since API 3, your application can safely call it and be assured that it will get similar behavior on both current and older versions of Android.

There is a setExact method, but this is a bit too specific. Aside from that it does not give me the option to have a certain interval (for repeating the alarm daily). Edit: After trying to go with setExact I found that this would require me to move up to API 19 (currently on 15), which is something I would like to avoid.


Question


Am I using the wrong class for this system? To me it seems like it should be a legit usage, but reading through the docs has left me wondering. Is there perhaps another class which is better suited for this system?

回答1:

You can separate before API 19 and after API 19. While setting alarm for the first time:

            if (Build.VERSION.SDK_INT >= 19) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mondayIntent);
            } else {
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                        AlarmManager.INTERVAL_DAY * 7, mondayIntent);
            }

When you catch the alarm:

    if (Build.VERSION.SDK_INT >= 19) {
        rescheduleAlarm();
    }

You must set the alarm with

setexact

again in rescheduleAlarm.

Hope this helps.