Android取消待处理的意图无效

时间:2016-08-18 02:46:14

标签: android android-pendingintent

我正面临这个非常奇怪的问题。我做了一个工作报警系统。但当我删除警报时,它会调用它。

AlarmBuddy.java(工作类设置原始警报)

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, m-1);
    calendar.set(Calendar.DAY_OF_MONTH, d);
    calendar.set(Calendar.HOUR, 8);
    calendar.set(Calendar.MINUTE, repeat%60);
    final Intent myIntent = new Intent(this.context, AlarmMiddle.class);
    myIntent.putExtra("name", name);
    myIntent.putExtra("id", repeat);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    super.onBackPressed();

    PendingIntent pending_intent = PendingIntent.getBroadcast(AlarmBuddy.this, repeat, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);

ListRecord.java THE FLAW

public Boolean cancelAlarm(int id){
    Intent myIntent = new Intent();
    PendingIntent.getBroadcast(context, id, myIntent,
            PendingIntent.FLAG_CANCEL_CURRENT).cancel();
    return false;
}

此功能用于取消闹钟。这有一些问题要再说一遍:

代码可以设置和调用警报。但是当我从DIFFERENT类中删除它时,它会立即调用警报。也许我只是一个菜鸟。或许这是一个无法解决的问题。

2 个答案:

答案 0 :(得分:2)

这在我的申请see link

中完全适用于我
 Intent intent = new Intent(getBaseContext(), Your_Service.class);
 PendingIntent pendingIntent = PendingIntent.getService(getBaseContext(), reqcode, intent, 0);
 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
 alarmManager.cancel(pendingIntent);

答案 1 :(得分:1)

要取消闹钟,您需要使用与设置时相同的PendingIntent。您还应该告诉AlarmManager取消闹钟以及取消PendingIntent。试试这个:

public Boolean cancelAlarm(int id) {
    Intent myIntent = new Intent(context, AlarmMiddle.class);
    PendingIntent pending_intent = PendingIntent.getBroadcast(context, id, myIntent,
                     PendingIntent.FLAG_NO_CREATE);
    if (pending_intent != null) {
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pending_intent);
        pending_intent.cancel();
    }
    return false;
}