Android重复闹钟在接下来的几天内无效

时间:2018-03-25 13:20:22

标签: android notifications alarmmanager

我想在某些时段每天发送通知。它在我创造警报的那一天工作。但接下来的几天我没有得到任何通知,我的ReminderClass也没有触发。我用谷歌搜索它,但无法解决问题。

我尝试使用setInexactRepeating代替setRepeating,但我仍然面临这个问题。

这是我的代码:

public void setRecurringAlarmsForPeriod(Integer sh, Integer sm, Integer    eh, Integer em, Integer interval)
{

    this.interval = interval;
    startHour = sh;
    startMinute = sm;
    endHour = eh;
    endMinute = em;
    reminderCount = 0;
    Integer currentStartHour = startHour;
    Integer currentStartMinute = startMinute;

    while (currentStartHour < endHour || (currentStartHour.equals(endHour) && currentStartMinute <= endMinute))
    {
        setRecurringAlarm(currentStartHour, currentStartMinute, reminderCount);
        reminderCount++;

        currentStartMinute += interval;
        if (currentStartMinute >= 60)
        {
            currentStartMinute -= 60;
            currentStartHour++;
        }
    }


    savePersistent();
}

在下面的代码中我通过alarmmanager在一天中的某些时段创建警报

private void setRecurringAlarm(Integer hour, Integer minute, Integer index)
{


    Calendar notificationTime = Calendar.getInstance();
    notificationTime.set(Calendar.HOUR_OF_DAY, hour);
    notificationTime.set(Calendar.MINUTE, minute);
    notificationTime.set(Calendar.SECOND, 0);
    notificationTime.set(Calendar.MILLISECOND, 0);

    Intent intent = new Intent(MainActivity.activity.getApplicationContext(), WaterReminderReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.activity.getApplicationContext(), index, intent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) MainActivity.activity.getSystemService(Context.ALARM_SERVICE);

    if (alarmManager != null)
    {
        try {

            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, notificationTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

        }
        catch (Exception e)
        {
            Crashlytics.log(Log.ASSERT, "exceptipon   :" , e.toString());
        }

        Crashlytics.log(Log.ASSERT, "Alarm Set For", hour + " " + minute);
        Crashlytics.log(Log.ASSERT, "Alarm Date", notificationTime.getTime().toString());

    }
    else
    {
        Crashlytics.log(Log.ASSERT, "ALARMS", "WAS NULL");
    }




}

1 个答案:

答案 0 :(得分:0)

我改变了这段代码

PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.activity.getApplicationContext(), index, intent, PendingIntent.FLAG_ONE_SHOT);

然后它起作用了。

 PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.activity.getApplicationContext(), index, intent, 0);