AlarmManager cancel multiple events - android

i'm developing an application where i need to set multiple alarm in a day.
Every time my application receives Intent.ACTION_DATE_CHANGE or Intent.ACTION_BOOT_COMPLETED i schedule schedule the alarms for the current day.
Users from the application preferences can change if they want to receive alarm based reminders for each event category.
How can i cancel all the alarm just for a single category?
Actually I schedule events in this way:
AlarmManager alarmMan = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
for (MyCustomEvent evt : events) {
Intent intentEvt = new Intent(context, ReceiverNotificationPublisher.class);
// the id is long value
intentEvt.putExtra(ReceiverNotificationPublisher.ITEM_ID, evt.getId());
// the category is int value
intentEvt.putExtra(ReceiverNotificationPublisher.ITEM_CATEGORY, evt.getCategory());
// others values here
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, evt.getCategory(), intentEvt, PendingIntent.FLAG_UPDATE_CURRENT);
// set event
alarmMan.setExact(AlarmManager.RTC_WAKEUP, evt.getTimestampMillis(), pendingIntent);
}
Thanks to everyone in advance

Related

Use one alarm manager to cancel another

I am doing a reminder application. It will reminder for a duration at the interval of time. For example, remind every five minutes for an hour. In this case, I am trying to set two alarm. One is used to do the reminder for every five minutes, the other one is used to cancel the reminder alarm after one hour. Here is my codes.
private void createIntervalNotification(int reminder, int dhour, int dminute){ //reminder in min
int interval = (reminder)*60*1000;
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+interval, interval, getPendingIntent(this,REMINDER_ID));
int duration = (dhour*60 + dminute)*60*1000;
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+duration,getPendingIntent(this,CANCEL_REMINDER_ID));
}
private static PendingIntent getPendingIntent(Context ctxt, int id) {
Intent intent1 = new Intent(ctxt, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctxt, id,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
I have some questions to do this(Set reminder of 5 mins for duration of 1 hour).
1) Can I do this with my method? Use one alarm to cancel another?
2) Can both alarm share a broadcastReceiver? If yes, how to differentiate it is invoked by which alarm?
3) Is it any other method can do this?
Cancelling an alarm is pretty much exactly the same as setting an alarm. You just call a different method to cancel on the AlarmManager than you do to create. Just make sure that the pending intent in the AlarmManager and the broadcast ID is identical.
Differentiate alarms by setting Extras on the Intent.

how to check if there is a notification just like the one im creating

the app i'm doing have to schedule an notifications if the user choose to
every time the user close the app the must must check and make the notification based on the user choice
the problem is if the user choose to have notification every time he close the app my code will put new notification for the same the thing so when the notification is fired there will be many notification instead of just one
i need to know if i can check if there is scheduled notification just like the one that i'm trying to make to avoid duplication and have one notification only
here is my code:
private void createScheduledNotification(long dateop,int days,String vaa,String naa)
{
Calendar calendars = Calendar.getInstance();
calendars.setTimeInMillis(dateop);
if(days<30){
calendars.add(Calendar.HOUR_OF_DAY, days *24);
}
else{
calendars.add(Calendar.MONTH, days/30);
}
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, TimeReceiver.class);
intent.putExtra("username", naa);
intent.putExtra("vaccine", vaa);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendars.getTimeInMillis(), pendingIntent);
}

Create alarm service in android for multiple times

in my task application, i want to create alarm service for multiple items. Here is the code i followed to create service. Lets assume, if there are more than 5 items present in list. then we will sent alarm service for 5 different times.
What if the user comes and edits the time?, how to update the system and make sure it triggers at new instance?. What if the user delete the task, how to quickly removes the registered alram for the deleted task?
What about uninstalling the app?, how to clear all the entries?, what if the system re-boots?
This is the code i'm following to register the task in alram services
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.MONTH, 8);
Calendar_Object.set(Calendar.YEAR, 2012);
Calendar_Object.set(Calendar.DAY_OF_MONTH, 6);
Calendar_Object.set(Calendar.HOUR_OF_DAY, 14);
Calendar_Object.set(Calendar.MINUTE, 25);
Calendar_Object.set(Calendar.SECOND, 0);
Step 2:
We need to create an alarm which help us to invoke the BroadCastReceiver on our specified time.
// MyView is my current Activity, and AlarmReceiver is the BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MyView.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
The following sets the Alarm in the specific time by getting the long value of the alarm date time which is in calendar object by calling the getTimeInMillis(). Since Alarm supports only long value , we're using this method.
*/
alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),
pendingIntent);
Use this method to set Alarm :
public static void startAlarm(Context context, int alarm_code, String time) {
String[] arrTime = time.split(":");
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
PendingIntent mAlarmSender = PendingIntent.getBroadcast(context,
alarm_code, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeZone(TimeZone.getDefault());
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arrTime[0]));
cal_alarm.set(Calendar.MINUTE, Integer.parseInt(arrTime[1]));
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, mAlarmSender);
}
Here,"int alarm_code" is your unique code for particular item.
And for update alarm first cancel the existing alarm and set new alarm for new time.For that use this method :
public static void cancelAlarm(Context context, int alarm_code) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
am.cancel(PendingIntent.getBroadcast(context, alarm_code, intent, 0));
}
Here,"int alarm_code" will be your unique code which you have used to set alarm.So that alarm with particular alarm_id will be cancel.You can also delete alarm with this method.
Same way you can clear all the alarms passing alarm_code to the given function.
You have to register receiver for system reboot and in onReceive of register you have to set all alarms again.
Hope this will help you.

cancel a particular alarm

I am setting alarms at diffrent time . I want to delete a particulat alarm.
Ex. I set 100 alarms at diiferents times , now I want to Delete an alarm set at 25 Feb 2012 10.45 AM. How Can I do that.
I written following code to set alarm.
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
GregorianCalendar gc=new GregorianCalendar();
gc.set(2012, 1, 22, 10, 42,0);
Intent intent = new Intent(this, AlarmService.class);
gc.set(Calendar.AM_PM,0);
final PendingIntent sender = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, gc.getTimeInMillis(), sender);
I have a broadcast receiver to recieve the alarm.
You need to save the request code of alarm,that is 1 in your case here. The 2nd parameter you pass in your PendingIntent.getBroadcast() method is your request code for a particular alarm.So when you save request code along with the time for what you set alarm,it would be easy for you to get the particular alarm instance and then you can cancel it using:
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, OneShotAlarm.class); //OneShotAlarm is the broadcast receiver you use for alarm
PendingIntent sender = PendingIntent.getBroadcast(context,alarm_request_code, intent, 0);
am.cancel(sender);
You should take care that each of your request code for different alarms should be unique,otherwise your alarm will be rescheduled with new time you set with the older request code.
Hope you get the point.
You might need to store it in some form of data structure to keep track of the time and the object. That being said, I have not tried storing AlarmManager objects before.

How to set multiple alarms using alarm manager in android

I'm building an alarm application. I have successfully implemented basic alarm functions.
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY, sHour);
calendar.set(calendar.MINUTE, sMin);
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
long sdl = calendar.getTimeInMillis();
Intent intent = new Intent(AlarmList.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmList.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager ALARM1 = (AlarmManager)getSystemService(ALARM_SERVICE);
ALARM1.set(AlarmManager.RTC_WAKEUP, sdl, sender);
In my application, user can select days (sunday,monday...) to repeat the alarm weekly.
I'm trying to create multiple alarms to repeat weekly but don't know how to do it.
Can I create it using (repeat) interval or should I create multiple alarm managers?
You need to use different Broadcast id's for the pending intents. Something like
this:
Intent intent = new Intent(load.this, AlarmReceiver.class);
final int id = (int) System.currentTimeMillis();
PendingIntent appIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_ONE_SHOT);
Using the system time should be a unique identifier for every pending
intent you fire.
From the docs:
If there is already an alarm for this Intent scheduled (with the
equality of two intents being defined by filterEquals(Intent), then
it will be removed and replaced by this one
Multiple AlarmManagers would not resolve your issue. If they have multiple different alarms (different times and different days), then you would need to set the alarm within the BroadcastReceiver every time you fire off a previous alarm.
You would also need to hold RECEIVE_BOOT_COMPLETED and have a BroadcastReceiver to receive the boot so that if the phone is rebooted you can re-schedule your alarms.
To set multiple alarms you need to define your Intent each time so that it is distinguishable from the others. The easiest way I find to do this is to set the data field of your Intent something as follows:
// give your alarm an id and save it somewhere
// in case you want to cancel it in future
String myAlarmId = ...;
// create your Intent
Intent intent = new Intent(AlarmList.this, AlarmReceiver.class);
intent.setData(Uri.parse("myalarms://" + myAlarmId));
...
The rest of your code #Hassy31 is fine as is and remains unchanged.
Note that the requestCode parameter in the PendingIntent.getBroadcast() method (as suggested by #parag) is unused according to the documentation so this ain't the right way to go about it.
set Broadcast id for pendingIntent
for (int id = 0; id < 3; id++) {
// Define pendingintent
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id,ntent, 0);
// set() schedules an alarm
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
}
Set multiple alarms using android alarm manager
//RC_ARRAY is store all the code that generate when alarm is set
private lateinit var RC_ARRAY:ArrayList<Int>
//tick is just hold the request when new alarm set
private var tick :Int=0
//setAlarm method set alarm
fun setAlarm(c: Calendar, context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//when alarm store set the request assign to tick variable
tick = System.currentTimeMillis().toInt()
//Add all the alarm Request into RC_ARRAY for just cancel the alarm
RC_ARRAY.add(tick)
//Notification Broadcast intent
val intentAlarm = Intent(context, AlaramFireReceiver::class.java).let {
PendingIntent.getBroadcast(context, tick, it, PendingIntent.FLAG_ONE_SHOT)
}
//alarm fire next day if this condition is not statisfied
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1)
}
//set alarm
manager.setExact(AlarmManager.RTC_WAKEUP, c.timeInMillis, intentAlarm)
}
//remove specific alarm
private fun removeAlarm(context: Context) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//remove specific alarm according to alarm request code
for (i in RC_ARRAY){
val intentAlarm = Intent(context, AlaramFireReceiver::class.java).let {
PendingIntent.getBroadcast(context, i, it, 0)
}
//cancel alarm
manager.cancel(intentAlarm)
}
}
//delivers notification for alarm
class AlaramFireReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
//Notification ID
val channelid="channelId"
val manger=context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//check for device only available for Oreo and above
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
val channel= NotificationChannel(channelid,"alarm notification",NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
manger.createNotificationChannel(channel)
}
//build notification
val build=NotificationCompat.Builder(context,channelid)
.setSmallIcon(R.drawable.ic_access_time_black_24dp)
.setContentTitle("alarm")
.setContentTitle("time done")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(Color.RED)
//Deliver notification
manger.notify(0,build.build())
}
}
What I do is something similar to how you move to the next element in a linked list. I keep in database a ReminderEntity that has all the days of the week the user enabled the Alarm to go off.
Then I schedule the first day only. When the first day triggers then in that moment I schedule the next day and so on.
Same thing if the user deletes the first coming Alarm before it happens. In this case I clear the removed day from the entity and schedule an alarm for the next one available.
use different requestCode for the pending intents and use .FLAG_MUTABLE for type of Flag
int requestCode = (int) System.currentTimeMillis();
Intent intent = new Intent(load.this, AlarmReceiver.class);
return PendingIntent.getBroadcast(this, requestCode , intent, PendingIntent.FLAG_MUTABLE);

Categories

Resources