16

I have created the alarm as shown below

Intent intent = new Intent(this, Areceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, timenow, 3000, sender);

I created a button to stop the alarm. In the onclick method i have written the following code

Intent intentstop = new Intent(this, Areceiver.class);
PendingIntent senderstop = PendingIntent.getBroadcast(this,
            0, intentstop, 0);
AlarmManager alarmManagerstop = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManagerstop.cancel(senderstop);

But the job is not stopping. What might be the issue?

sankara rao bhatta
  • 649
  • 5
  • 9
  • 13

1 Answers1

33

You gave your Pending intent a request_code = 1234567 when you start the alarm. But you are using 0 when you try to stop it. Use this when trying to stop and should work

Intent intentstop = new Intent(this, Areceiver.class);
PendingIntent senderstop = PendingIntent.getBroadcast(this,
            1234567, intentstop, 0);
AlarmManager alarmManagerstop = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManagerstop.cancel(senderstop);
bytebender
  • 7,371
  • 2
  • 31
  • 54
  • 1
    This helped me too. Although, my intenet started a service so instead of using PendingIntent.getBroadcast, I used PendingIntent.getService. Thanks! – Asim Apr 01 '13 at 10:21
  • Is there any method that is guaranteed to be called on the service? Unfortunately `onDestroy` is not called in my case – Niklas May 01 '15 at 20:13