5

I am able to create and cancel an alarm with the code below. I want to create more than one alarm. Alarm times comes from an arraylist. In this arraylist I would like to create an alarm for each date. And presses of the cancel button will cancel only the current alarm. How can I do it?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    setOneTimeAlarm(); 

    buttonCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);

            // Tell the user about what we did.
            Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
        }
    });
}

private void setOneTimeAlarm() {
    Intent intent = new Intent(this, AReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
TimWolla
  • 31,849
  • 8
  • 63
  • 96
realuser
  • 931
  • 2
  • 15
  • 26

2 Answers2

3

I'll post an example with a way I did it in one of the apps I created.

When calling the alarm you need to send an extra id like this: Tmp is an object which has a unique ID.

Intent intent = new Intent(DisplayActivity.this,AlarmReciever.class);

intent.setData(Uri.parse("timer:"+tmp.getId()));

PendingIntent pendingIntent = PendingIntent.getBroadcast(DisplayActivity.this,1, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);

and then you retrieve the id with this line:

Long.parseLong(intent.getData().getSchemeSpecificPart())

When cancelling just create the same pending intent with the ID and call alarmmanager.cancel()

Edit:

To cancel the specific alarm on the item the user clicked on (here is where tmp.getId comes in handy) I just used this code, I think you need to create the same pendingIntent to be able to cancel the specific alarm.

 Intent intent = new Intent(DisplayActivity.this,AlarmReciever.class);
 intent.setData(Uri.parse("timer:"+tmp.getId()));
 PendingIntent pendingIntent = PendingIntent.getBroadcast(DisplayActivity.this,1, intent, 0);
 AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
 am.cancel(pendingIntent);

AlarmReciever is my BroadcastReceiver. DisplayActivity is the activity itself.

It's in AlarmReciever I have the following code:

Long.parseLong(intent.getData().getSchemeSpecificPart())
David Olsson
  • 8,085
  • 3
  • 30
  • 38
  • Thank for answer David but I don't understand how I will set list of dates in AlarmManager. – realuser Jul 08 '11 at 07:27
  • Why do you want a list? This creates several different alarms, just put different values in calendar object. I keep a reference of all the alarms in a local database to be able to show them and cancel them all. Loop through and call alarmmanager.set on several or what exactly do you mean? – David Olsson Jul 08 '11 at 07:33
  • I think I have same problem. I have service from where I set alarms. If I set more than one alarm, only the last one works. So I don't get it: if I want to set more than one alarm, I should use IDs, or IDs are only for canceling purpose? – Mario Jul 08 '11 at 07:45
  • To be able to set several alarms you need ID like I put in the answer. Otherwise you will only get the last one. So it's for being able to have several. – David Olsson Jul 08 '11 at 08:17
  • What's your other problem? A new one or is it because of the solution? – David Olsson Jul 08 '11 at 12:38
  • How do you know Alarm size to cancel all existing alarm? – realuser Jul 08 '11 at 15:49
  • What do you mean? How to know all the ids so you can create pending Intents able to cancel them all? I stored all the ids in a database. – David Olsson Jul 09 '11 at 07:11
  • Jeez, i have the same problem now with the multiple alarms, but i don't understand you answer David. How do i declare tmp? – erdomester Jul 09 '11 at 08:12
  • You can declare and use like this: MainActivity tmp = new MainActivity(); intent.setData(Uri.parse("timer:"+tmp.getId())); – realuser Jul 09 '11 at 12:04
  • David, I used following code to cancel all alarm but only one of them was canceled: Long.parseLong(intent.getData().getSchemeSpecificPart()); alarmManager.cancel(pendingIntent); Can we do without using database? – realuser Jul 09 '11 at 12:16
  • @erdomester, tmp is just my own object in that example. It's an objects which contains data parsed from a webservice. It doesnt matter as long as the id is unique I think. – David Olsson Jul 09 '11 at 15:26
  • @realuser, I edited my answer above to provide an example to be able to cancel the event (a specific event). Since my solution is based on 0 to endless of alarms. However only 1 per id (tmp.getId()). It all depends on where you get your numbers from and the exact implementation of the alarm manager. You probably need to keep some kind of reference to the different ids if you want them to be able to be cancelled individually, otherwise just have an incremented number and try all numbers. Read more about storing data here: http://developer.android.com/guide/topics/data/data-storage.html – David Olsson Jul 09 '11 at 15:32
  • I've used this method ok. but one thing that had me stuck for hours, was that I was missing IntentFilter.addDataScheme("timer") when registering my BroadcastReciever (I do it in code, not the manifest) – SteelBytes Aug 26 '11 at 07:03
1

This is on continuation of David's reply on how to get unique ID.

The unique ID can come from the SQLITE table. While creating the table to store the reminder date and time, have an _ID column with AUTOINCREMENT. When rows are inserted, this column will automatically get one-up numbers and unique ones. The table will also help you store the reminders for you in case the device is switched off and you want to recreate the reminders again. On device shutdown, I think alarms will get lost.

CREATE TABLE IF NOT EXISTS reminder_datetime
_ID INTEGER PRIMARY KEY AUTOINCREMENT,
NOTIF_DATETIME INTEGER;

To work with setting and getting dates from the table, use Calendar object:

Calendar cal = Calendar.getInstance();

Then you can use, cal.setTime or cal.setTimeInMillis functions. Similarly, get functions to get the date.

Use date format if want to format the date to readable one:

myDate = android.text.format.DateFormat.format("MM/dd/yyyy", cal.getTimeInMillis()).toString();
inder
  • 551
  • 1
  • 5
  • 9