TheLettuceMaster
TheLettuceMaster

Reputation: 15734

I am unable to cancel Alarms/PendingIntents in Android

In my main activity, I have a method setRepeatingAlarm() to set the Alarms when the app first loads. That method successfully sets the Alarms by looping through a column and taking an integer value from each row in a SQLite table. Here is the method in basic:

 for (int i : AlarmDays) {


        Calendar cal = Calendar.getInstance();
        if (cal.get(Calendar.MINUTE) >= i)
            cal.add(Calendar.HOUR, 1);
        cal.set(Calendar.MINUTE, i);

        Intent intent = new Intent(ManageDebts.this, TimeAlarm.class);
        pendingIntent = PendingIntent.getBroadcast(this, i,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                60 * 60 * 1000, pendingIntent);
    }

After the Method is completed it then loops through the rows each again and puts each into a CustomAdapter (List) to display the data. Here is the context (again, in basic) in my onCreate in the main class:

    datasource = new DebtDataSource(this);
    datasource.open();

    **am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    setRepeatingAlarm();**

    values = datasource.getAllDebt();
    adapter = new MyArrayAdapter(this, values);
    setListAdapter(adapter);

I want the user to either long press a row and it will delete the item, or there is a button to delete all rows. Everything works, but I can not get the alarms to go away.

I understand HOW to do this (cancel method by setting same pendingIntent with the same extras), but my attempts have been foiled! and I dont know WHERE to put it? Everything above is in the same class.

Whether the user deletes one row or all, I think the easy way is to delete all Alarms and loop through that method again to reset them. Can anyone help out and tell me where to put this canceling code?

Upvotes: 1

Views: 496

Answers (1)

Abhi
Abhi

Reputation: 9005

In Long click of the List

PendingIntent pi = PendingIntent.getBroadcast(context, unique_id, i, 0);
am.cancel(pi);

unique_id is seperate for every pending intent so get the listview id , add +1 so that it will be your pending intent ID.

So that that particluar PendingIntent will be deleted.

To Cancel all the alarms Make a for loop simply as you set the alarm and Cancel them.

Upvotes: 5

Related Questions