Вот пример моей тестовой реализации создания и отмены тревоги.
public void setTHEalarm(Calendar aCalendarToAlarm) {
int id;
Intent intent;
PendingIntent pendingIntent;
AlarmManager alarmManager;
//I create an unique ID for my Pending Intent based on fire time of my alarm:
id = Integer.parseInt(String.format("%s%s%s%s",
aCalendarToAlarm.get(Calendar.HOUR_OF_DAY),
aCalendarToAlarm.get(Calendar.MINUTE),
aCalendarToAlarm.get(Calendar.SECOND),
aCalendarToAlarm.get(Calendar.MILLISECOND))); //HASH for ID
intent = new Intent(this,AlarmReceiver.class);
intent.putExtra("id",id); //Use the id on my intent, It would be usefull later.
//Put the id on my Pending Intent:
pendingIntent = PendingIntent.getBroadcast(this,id,intent,0);
alarmManager = (AlarmManager)
this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,aCalendarToAlarm.getTimeInMillis(),CustomDate.INTERVAL_MINUTE,pendingIntent);
Log.w(TAG+" Torrancio","Created alarm id: "
+id+" -> "
+CustomDate.dateToHumanString(aCalendarToAlarm.getTime()));
//Keep a reference in a previously declared field of My Activity (...)
this.idSaved = id;
}
//Now for canceling
public void setCancel() {
int id;
Intent intent;
PendingIntent pendingIntent;
AlarmManager alarmManager;
id = this.idSaved;
intent = new Intent(this,AlarmReceiver.class);
intent.putExtra("id",id);
pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_CANCEL_CURRENT);
//Note I used FLAG_CANCEL_CURRENT
alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Log.w(TAG+" Torrancio","Canceled->"+id);
}
нужно 3 вещи,
- Тот же тип намерения (в данном случае речь идет о AlarmManager ).
- Тот же идентификатор PendingIntent (сохраните ссылку на идентификатор, сохраните ее каким-либо образом).
- Правильный флаг ( FLAG_CANCEL_CURRENT для отмены, не нужно и не должен быть точно тем, который вы использовали при создании pendingintent [, потому что мы используем флаг отмены для calcel, но не create. ])
Для более подробной информации, пожалуйста, проверьте это из.
Надеюсь, это поможет.