3

这工作正常:

Intent intent = new Intent(HelloAndroid2.this, AlarmReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(HelloAndroid2.this, 0,
    intent, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (12 * 1000), pendingIntent);

这行不通。我只听到一次警报。

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (12 * 1000), 3 * 1000, pendingIntent);

我也试过这个,没有运气:

Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 5);

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

问题是什么?

4

2 回答 2

5

来自FLAG_ONE_SHOT的PendingIntent 文档:

这个 PendingIntent 只能使用一次。如果设置,则在调用 send() 后,它将自动为您取消,并且将来通过它发送的任何尝试都将失败。

所以在第一次触发pendingIntent后,它会被取消,并且下一次通过警报管理器发送它的尝试将失败

尝试使用 FLAG_UPDATE_CURRENT

于 2011-01-15T14:49:01.993 回答
0

按顺序查看您的代码示例:

在您的第一个示例中,您使用的是 AlarmManager.set - 这严格用于一次性警报,所以是的,它只会触发一次。如果您想使用 AlarmManager.set,那么触发的代码应该做的最后一件事是设置一个新的警报(它也应该使用一个新的 PendingIntent)。

在您的第二个示例中,您正在使用重复警报。您不需要在每次触发时创建新的 PendingIntent,因为操作系统会处理警报的重复方面。

您的警报没有理由不应该每 3 秒重复一次,因此我将开始查看您为处理警报而编写的 BroadcastReceiver 实现。

检查您是否正确实施了它。注释掉 onReceive() 方法中的所有代码,而是让它写一条日志消息。每次警报触发时,一旦您看到日志消息出现在 logcat 中,请将代码重新添加(保留日志消息),并将另一条日志消息添加到方法的末尾。这使您可以查看方法执行所需的时间 - 您希望在警报再次触发之前完成它以避免任何意外的副作用。

顺便说一句,如果你想要一个重复的警报,android.os.Handler 是一种更有效的方法,尽管通过 AlarmManager 设置的警报确实会非常准确地触发。

于 2011-07-18T19:25:47.643 回答