Delete alarm from AlarmManager using cancel() - Android

↘锁芯ラ 提交于 2019-11-26 15:19:57
Govil

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);
    }
Anurag Mishra

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);

If you want to cancel the alarm manager just put the wright id in pending intent and just call cancel() in alarm manager for that pending intent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!