BroadcastReceiver 延迟触发

BroadcastReceiver fires with a delay

我有一个 TimePicker 和一个 Button,我想在用户在指定时间点击 Button 时设置一个闹钟。

当我点击按钮时它得到了小时,但警报有时会在指定时间触发,但并非总是如此。它在指定时间触发的次数少于未触发的次数。大多数情况下 BroadcastReceiver 不会在指定时间触发,它会延迟触发。

这是我现在拥有的代码:

On Alarm class(代码引用 BroadcastReceiver)

AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

Calendar cal= Calendar.getInstance();

cal.set(Calendar.MONTH,cal.get(Calendar.MONTH));
cal.set(Calendar.YEAR,cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_MONTH,cal.get(Calendar.DATE));
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,minutes);


alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 5, alarmIntent);

其中 hourminutes 是从 TimePicker 检索到的小时和分钟。

在 AlarmReceiver 上 class

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("prove", "We enter on BroadcastReceiver");
    }
}

在Manifest.xml

<receiver
    android:name=".AlarmReceiver"
    android:enabled="true" >
</receiver>

例如,在显示 BroadcastReceiver 的日志之前,我已经放置了一个日志来查看我从 TimePicker 检索的时间。我在 16:48(在 TimePicker)点击了它,结果是:

12-06 16:47:02.951 7980-7980/com.project.user.project D/prove: hour: 16:48
12-06 16:50:23.727 7980-7980/com.project.user.project D/prove: We enter on BroadcastReceiver
12-06 17:00:01.070 7980-7980/com.project.user.project D/prove: We enter on BroadcastReceiver

如您所见,BroadcastReceiver 已在 16:5017:00 处发射了两次,而我认为它们应该在 16:48 和 [=29] 处发射=] 因为我已经设置它们之间会延迟 5 分钟,而不是像本例中那样延迟 10 分钟。

那么,我该怎么做才能在准确的时间触发警报而不是延迟触发?我是否缺少某些配置?

提前致谢!

使用setInexactRepeating

alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 1000 * 60 * 5, alarmIntent);

你可以检查我的代码,我在 app.I 中所做的工作非常完美。

pendingIntent = PendingIntent.getBroadcast(this, _id, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeToAlarm, AlarmManager.INTERVAL_DAY, pendingIntent);

有帮助吗..

如前所述 in the documentationsetRepeating 不准确。

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

因此,要在 API 19 的确切时间触发警报,请使用 setExact,并在每个警报中设置下一个警报。

Schedule an alarm to be delivered precisely at the stated time.