简体   繁体   English

AlarmManager不创建警报

[英]AlarmManager not creating an alarm

I'm attempting to add some "reminders" functionality to my app. 我正在尝试向我的应用程序添加一些“提醒”功能。 I want to set up an AlarmManager and fire a Notification when the alarm happens. 我想设置一个AlarmManager并在发生警报时触发Notification

I've added a few methods to create an alarm, cancel an alarm, and see if an alarm is active. 我添加了一些方法来创建警报,取消警报以及查看警报是否处于活动状态。

The following code is in Settings.class which extends Activity : 以下代码位于Settings.class ,该代码扩展了Activity

private boolean getRemindersEnabled() {
    return (PendingIntent.getBroadcast(this,
            1,
            new Intent(this, Main.class),
            PendingIntent.FLAG_NO_CREATE) != null);
}

private void enableReminders() {
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, Main.class);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, mDayStart);
    calendar.set(Calendar.MINUTE, 0);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            SIXY_MINUTES,
            alarmIntent);

    mRemindersEnabled = getRemindersEnabled();
    populateReminders();
}

private void disableReminders() {
    AlarmManager service = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, Main.class);
    PendingIntent pending = PendingIntent.getBroadcast(this,
            0,
            intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    service.cancel(pending);

    mRemindersEnabled = getRemindersEnabled();
    populateReminders();
}

When I call enableReminders() , it creates the alarm. 当我调用enableReminders() ,它将创建警报。 However, getRemindersEnabled() returns false. 但是, getRemindersEnabled()返回false。 Is there something I'm failing to do? 有什么我做不到的吗?

getRemindersEnabled() should use the same requestCode from the PendingIntent that creates the Alarm. getRemindersEnabled()应该使用与创建警报的PendingIntent中相同的requestCode In this case, you are using 1 , the correct will be 0 . 在这种情况下,您使用1 ,正确的将是0

private boolean getRemindersEnabled() {
    return (PendingIntent.getBroadcast(this,
            0,
            new Intent(this, Main.class),
            PendingIntent.FLAG_NO_CREATE) != null);
}

[EDIT] [编辑]

To cancel the Alarm, before calling service.cancel(intent); 要取消警报,请致电service.cancel(intent); , call pending.cancel(); ,调用pending.cancel(); using the flag FLAG_UPDATE_CURRENT 使用标志FLAG_UPDATE_CURRENT

PendingIntent pending = PendingIntent.getBroadcast(this,
        0,
        intent,
        PendingIntent. FLAG_UPDATE_CURRENT);
pending.cancel();
service.cancel(pending);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM