Pooja Balakrishnan
Pooja Balakrishnan

Reputation: 145

Dismissing and deleting an alarm

I want to dismiss an alarm and also delete an alarm in 2 different Activities.What functions would I use for both? alarmmanager.cancel() dismisses or deletes the alarm?

I have written this code:

Button DeleteButton = (Button) this.findViewById(R.id.dismiss_button);
    DeleteButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Build Intent and Pending Intent to Set Snooze Alarm
            Intent AlarmIntent = new Intent(AlarmActivity.this,
                    AlarmReceiver.class);
            AlarmManager AlmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            PendingIntent Sender = PendingIntent.getBroadcast(
                    AlarmActivity.this, 0, AlarmIntent, 0);
            AlmMgr.cancel(Sender);
            finish();

        }

    });

The app is crashing when I run this. Can anyone kindly help?

Upvotes: 3

Views: 1219

Answers (1)

TheLastBert
TheLastBert

Reputation: 466

I think you will need to call the set method of alarmManager with your pending intent before you can cancel it e.g.

//Set an alrm for 5 seconds from now
AlmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000 ,Sender)
//Do stuff
...
//Cancel alarm
AlmMgr.cancel(Sender)

It's difficult to be sure without seeing your LogCat output, but I would guess that trying to cancel the alarm before it has been set is throwing an exception. According to the APIs, .cancel() will remove the alarm, so it will never go off:

http://developer.android.com/reference/android/app/AlarmManager.html#cancel(android.app.PendingIntent)

I can't confirm it will stop and cancel the alarm if it is in the process of sounding already, but you should be able to check this pretty easily.

Upvotes: 2

Related Questions