[FIXED] Unable to cancel the alarm from AlarmManager

Issue

I have an AlarmManager that notifies me every 10 seconds. Everything works just fine but for some reason I can’t cancel the alarm. Here’s my code.

public class AlarmNotifReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent)
{
//things
}

public void SetAlarm(Context context)
{
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmNotifReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10*1000, pi); // Millisec * Second
}

public void CancelAlarm(Context context)
{
    Intent i = new Intent(context, AlarmNotifReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pi);
}


}

as expected I call this CancelAlarm() method from my other classes but for some reason it does not cancel and keep notifying me like nothing happened.
Note: SetAlarm() also works just fine.

Thanks in advance.

Solution

Alarm should be created and cancelled on Same Pending intent.In your case you are creating Pending Intent Twice.

Your code should look like below.

public class AlarmNotifReceiver extends BroadcastReceiver {

    PendingIntent pi;
    AlarmManager am;
    Intent i;

    @Override
    public void onReceive(Context context, Intent intent) {
        pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        i = new Intent(context, AlarmNotifReceiver.class);
        //things
    }

    public void SetAlarm(Context context) {

        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pi);
    }

    public void CancelAlarm(Context context) {
        am.cancel(pi);
    }


}   

Answered By – Vipul

Answer Checked By – Mary Flores (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published