Delete alarm from AlarmManager using cancel() - Android
Try this flag:
PendingIntent.FLAG_UPDATE_CURRENT
Instead of:
PendingIntent.FLAG_CANCEL_CURRENT
So the PendingIntent will look like this:
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, alert.idAlert, intent, PendingIntent.FLAG_UPDATE_CURRENT)
(Make sure that you use same alert
object and mContext
!)
A side note: If you want one global AlarmManager, put the AlarmManager in a static variable (and initialize it only if it's null
).
Cancelling an alarm is a bit confusing. You have to pass the same ID and IntentPending. Here is an example:
private void resetIntentWithAlarm(int time){ Intent intentAlarm = new Intent(getApplicationContext(), DownloadService.class); intentAlarm.putExtra(Your Key, Your stuff to pass here); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService( getApplicationContext(), YOUR_ID, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT ); if (time != 0) { alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (60L * 1000L * time), (60L * 1000L * time), pendingIntent); Log.i(TAG, "Alarm setted on for " + time + " mins."); } // if TIME == Zero, cancel alaram else { alarmManager.cancel(pendingIntent); Log.i(TAG, "Alarm CANCELED. Time = " + time); }
Cancel the alarm from alarm manager on any specific time which you set:
Intent intent = new Intent(context, AlarmReceiver.class);PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);am.cancel(pendingIntent);