警报管理器无法在Android中重复

时间:2017-03-12 10:04:08

标签: android notifications alarmmanager

我正在尝试每天早上6点使用Android AlarmManager发送通知。通知有效一次,其他日子无效。

public class AlarmMsg extends WakefulBroadcastReceiver {
 // set the alarm
 public void setAlarm(Context context) {
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmMsg.class), 0);

    Calendar firingCal = Calendar.getInstance();
    Calendar currentCal = Calendar.getInstance();

    firingCal.set(Calendar.HOUR, 6); // hour
    firingCal.set(Calendar.MINUTE, 0); 
    firingCal.set(Calendar.SECOND, 0); 

    long intendedTime = firingCal.getTimeInMillis();
    long currentTime = currentCal.getTimeInMillis();

    if (intendedTime >= currentTime) {
        // set from today
        alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, alarmIntent);
    } else {
        // set from next day
        firingCal.add(Calendar.DAY_OF_MONTH, 1);
        intendedTime = firingCal.getTimeInMillis();

        alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, alarmIntent);
    }
}

并创建通知:

  @Override
    public void onReceive(Context context, Intent intent) {
    // notification builder
}

在我的主要活动中,我只是像这样调用setAlarm:

  new AlarmMsg().setAlarm(getApplicationContext());

这显示了早上6点的通知,但它只显示1个通知,并且在接下来的几天内不再重复。我希望通知每天早上6点显示。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果您收到一次警报,那么您就在正确的轨道上,只需记住使用setInexactRepeating警报类型,这样设备就会在熄灭时唤醒。如果您的警报不重要,也请考虑使用alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);

{{1}}