Android:无法取消AlarmManager

时间:2016-01-01 03:34:26

标签: java android android-intent alarmmanager

我似乎无法取消闹钟。我已经查看了Stack Overflow上的其他帖子,但没有一个对我有用。

这是我的代码:

AddAlarm类:

public void setAlarm(){
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(AddAlarm.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    calAlarm = Calendar.getInstance();
    Calendar calNow = Calendar.getInstance();
    Date date = new Date();

    calNow.setTime(date);
    calAlarm.setTime(date);
    calAlarm.set(Calendar.HOUR_OF_DAY, pickHour);
    calAlarm.set(Calendar.MINUTE, pickMinute);
    calAlarm.set(Calendar.SECOND, 0);

    if (calAlarm.before(calNow) || calAlarm == calNow){
        calAlarm.add(Calendar.DATE, 1);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        am.setExact(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), pi);
    }
}

public void cancelAlarm(){
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(AddAlarm.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    am.cancel(pi);
}

你们有什么建议吗?谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用此PendingIntent.FLAG_CANCEL_CURRENT而非PendingIntent.FLAG_UPDATE_CURRENT,如

PendingIntent pi = PendingIntent.getBroadcast(AddAlarm.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

答案 1 :(得分:1)

我认为您没有取消未决意图,请尝试以下代码段

 private void cancelAlarm(int alarmId)
{
    Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, alarmId,
            intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.cancel(sender);
    sender.cancel();
}

调用 cancelAlarm(0)方法取消闹钟