1

I have this...

button = (Button) findViewById(R.id.start_repeating);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(Test.this, RepeatingAlarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(Test.this, 0, intent, 0);
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 1 * 1000;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 1 * 1000, sender);
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(Test.this, "repeating_scheduled", Toast.LENGTH_LONG).show();
    }
});

button = (Button) findViewById(R.id.stop_repeating);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(Test.this, RepeatingAlarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(Test.this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(sender);
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(Test.this, "repeating_unscheduled", Toast.LENGTH_LONG).show();
    }
});

But it doesn't seems to work properly... each time I try clicking the second button the alarm doesn't cancel... This is the BroadcastReceiver i'm using...

public class RepeatingAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        for(int i=0;i<5;i++)
            Toast.makeText(context, "repeating_received " + i, Toast.LENGTH_SHORT).show();
    }
}

Please someone tell me what is wrong!!! Thanks!!

alois.wirkes
  • 369
  • 2
  • 7
  • 20

1 Answers1

2

If you save a reference to your pending intent then you can just use AlarmManager.cancel().

Pass in your pending intent and you are all set.

StoneBird
  • 1,900
  • 13
  • 12