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.
Related
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
I have an Alarm Manager that runs periodically , but I want to have a specific set of time that it will be running. For Example , lets say that we have a periodic Alarm Manager that is registered with a broadcast receiver and an Action is being performed every 30 minutes. The thing is that I want the Alarm Manager to be active for a specific time lets say 3 hours, so the Alarm manager should goes off 3 hours / 30 minutes or 6 times.
Code to start the define the Alarm Manager:
TimerPeriodic = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(),AlarmReceiver.class);
intent.putExtra(Constants.ALARM_ID, Constants.TIMER_PERIODIC_ID);
TimerPeriodicPendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
Fire Alarm Manager:
long start = TimeUnit.MINUTES.toMillis(StartMinutes);
TimerPeriodic.setRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + start, start, TimerPeriodicPendingIntent);
Also the alarm Manager should be active if the Application is killed.
Thank you for any help!
It can be acheived by using Sqlite Db. where you store the Alaram ID,count,and repeation (How many time you want to repeat).
when Alarm is trigger (AlarmReceiver.onReceive()) increment the count check with the condition with repeation. if it exceed just cancel it. Hope It will help :)
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(
context.ALARM_SERVICE);
Intent myIntent = new Intent(context, AlarmReceiver.class);
cancelAlarm(reminder.getId(),myIntent,alarmManager);
}
private void cancelAlarm(int notiId,Intent myIntent,AlarmManager alarmManager) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notiId, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
I have set alarm to get trigger after 60 seconds. but the alarm is getting triggered after 80/90 seconds (But not exactly after 60 seconds). How can i set alarm to get trigger exact at specified time?
//calling method to set alarm after 60 seconds
startAlarm(context, 1, System.currentTimeMillis()+60000);
//method defination
public static void startAlarm(Context context, int timerType, long nextScheduledTime) {
EABLog.d(TAG, " ~~~INSIDE START ALARM~~~~~ "+timerType);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(Constants.KEY_TIMER_TYPE, timerType);
intent.setAction(""+timerType);
PendingIntent pollPendingIntent = PendingIntent.getBroadcast(context,
timerType, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextScheduledTime,
pollPendingIntent);
EABLog.d(TAG, System.currentTimeMillis()+" ALARM IS SET AT "+nextScheduledTime+" TYPE :"+timerType);
}
//permission added in Android Manifest
<uses-permission android:name="android.permission.WAKE_LOCK"/>
As docs say about setExact - The alarm will be delivered as nearly as possible to the requested trigger time. So it is not as exact as you think :)
Look at public void setWindow (int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation) methods 3rd parameter - windowLengthMillis The length of the requested delivery window, in milliseconds. The alarm will be delivered no later than this many milliseconds after windowStartMillis.
This might do the trick :)
First off,this site is great and everyone is so helpfull. This is my first post so forgive me if i have ommited anything.
I create an alarm like so:
private void startLocation() {
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyWeatherUpdateService.class);
PendingIntent service = PendingIntent.getService(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
alarm.setRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + (60 * 1000),
Long.parseLong(prefs.getString("listpref", "60000")), service);
}
In this method which is called inside a fragment, context is from getApplication (), listpref is a string update interval in milliseconds.
I cancel it by:
public void endLocation() {
Intent i = new Intent(context, MyWeatherUpdateService.class);
PendingIntent service = PendingIntent.getService(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
alarm.cancel(service);
}
Ensuring that the intent/pending intent is the same.
Now i have 2 issues:
1) the alarm fires almost imediately after creation, even though i tell it to start after 1min.
2) when i call cancel, the alarm fires once more before the alarm is cancelled.
With question 1) why does the alarm fire so soon? And with 2) is this working as intended or should the alarm cancel immediately like i want it to.
If i have not supplied enough info, ill add more code if required.
Thanks in advance.
the alarm fires almost imediately after creation, even though i tell it to start after 1min
That is because you are using RTC with an elapsedRealtime() starting time. Those need to match. The simplest solution is to switch to ELAPSED_REALTIME.
when i call cancel, the alarm fires once more before the alarm is cancelled.
Try replacing PendingIntent.FLAG_CANCEL_CURRENT with 0, at least in the PendingIntent for your cancel() call.
I use this code to setup an alarm in our business application:
private void setupAlarm() {
final Context c = getApplicationContext();
final AlarmManager alarm =
(AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
final Intent i = new Intent(c, AlarmReceiver.class);
final PendingIntent sender =
PendingIntent.getBroadcast(c, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
final long startFromNow = System.currentTimeMillis()+10000;
final long timer = 5*60*1000;
alarm.setRepeating(AlarmManager.RTC_WAKEUP, startFromNow, timer, sender);
}
I cannot understand why the interval for the alarm is not respected. First alarm starts after 10 seconds (as expected), afterwards it starts every 2 minutes and a bit (122 seconds to 127 seconds), which is wrong. The interval is 5 minutes, or am I wrong?
I use this exact code in a simpler application: one activity that sets the repeating alarm and the receiver just creates a log. There it works.
What could make the AlarmManager act so different?
I have tried to:
use set() and in the alarm receiver use another set() for over 5 minutes: launch at 2 minutes
use setInexactRepeating() instead of setRepeating(): launch at 2 minutes
Any insight would be helpful. Thanks!
Immediate suggestion that comes to mind - make sure you don't set an alarm with the same intent and different value elsewhere. The intent need not be the same object, see the set methods documentation in AlarmManager.