How can create more than one alarm?

别说谁变了你拦得住时间么 提交于 2019-12-01 18:16:53

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())

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!