In my android app, I have two services which are supposed to run timely.
One will run on a fixed date and the other will run on 11:00 PM everyday.
To achieve this, I have created services and used Alarm manager to start them at fixed time.
private void scheduleAlarmForCleanup(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 00);
Intent pendingIntent = new Intent(this, CleanupService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, pendingIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);
}
Now I have called this function in my Activity's onCreate.
But onCreate can be called multiple times during a day
and my concern is this will lead to multiple calls to this function.
What effect can this have ?
Would the Alarm be set multiple times.
Is there a way by which I can check whether my alarm is already set and in that case I won't try to set alarm again.
Each time, you will have to try to cancel the alarm and set it again.
try
{
// This block will cancel the alarm if already available. Else throw an
// exception which will be ignored
alarmManager.cancel(pintent);
}catch (Exception ignored){ }
// After try block, set the manager again.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pintent);
Related
Below is the code I am using to create alarms when data is pulled from external API. If the time set is in the past, the alarm goes off as soon as it is set(2 second gap). For example if I set the alarm for 8:00 AM, 10th April at 10:00 AM on 11th April(Past time). It starts the alarm as soon as it is set.
public static final int ALARM_REQUEST_CODE = 1001;
public static AlarmManager alarmManager = (AlarmManager) EHCApplication.getInstance().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
public static Intent alarmIntent = new Intent(EHCApplication.getInstance().getApplicationContext(), AlarmReceiver.class);
public static PendingIntent pendingIntent = PendingIntent.getBroadcast(EHCApplication.getInstance().getApplicationContext(), ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
public static void setAlarm(Reminder rm) {
for (ScheduledTime time : rm.getScheduledTime()) {
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.ARGS_SELECTED_MEDICINE, medicine);
alarmIntent.putExtras(bundle);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMilliseconds(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
I am expecting the alarm to go off from next time it hit the time. Where am I making mistake?
This is the expected behavior.
From the documentation of setRepeating() (and other AlarmManager set methods):
If the stated trigger time is in the past, the alarm will be triggered
immediately
If you would like to prevent that happening, then simply do not set alarms with a past trigger time (e.g. check against System.currentTimeMillis() when setting the alarm).
Well, I ran into same problem and after studying I found that alarm will be run as soon when past time is set for the alarm.
Source: Here is documentation of Alarm Manager - setRepeating()
So, I resolved the issue by checking if "Calendar time is in past from system time than I add a day"
Working code:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alarmManager.cancel(pendingIntent);
// Check if the Calendar time is in the past
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
Log.e("setAlarm","time is in past");
calendar.add(Calendar.DAY_OF_YEAR, 1); // it will tell to run to next day
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); //Repeat every 24 hours
I have read many articles, but non seems to work for me!
I have to schedule a repeating task with AlarmManager for everyday at 7:15. The following method is set in an activity and registered a broadcast receiver for it!
private void setTask(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
updateTime.set(Calendar.HOUR_OF_DAY, 7);
updateTime.set(Calendar.MINUTE, 15);
Intent intent = new Intent(context, NotifyUpdate.class);
PendingIntent fireAlarm = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(alarms.RTC_WAKEUP, updateTime.getTimeInMillis(), alarms.INTERVAL_DAY, fireAlarm);
}
The problem is when I run the app the method gets executed immediately regardless of the time set, but not executing at (7:15).
Any Idea?
Try this before setting alarm
Calendar now = Calendar.getInstance();
if (updateTime.before(now)) {
updateTime.add(Calendar.DAY_OF_MONTH, 1); // if its in the past increment
}
alarms.setRepeating(alarms.RTC_WAKEUP, updateTime.getTimeInMillis(), alarms.INTERVAL_DAY, fireAlarm);
You said that you have immediate triggering not depending on time. It's happening because updateTime-object references at time in the past, so the goal is to set an alarm to 7:15 in the future. This will help to avoid immediate triggering.
If I call the setinexactrepeating() alarm method in the onCreate , how does it affect the alarm which is being repeated at the specified interval
Here is the code of setting alarm, I am calling this method in the onCreate()
public void setAlarm()
{
Intent myintent=new Intent(this,AlarmReciever.class);
Random random = new Random();
int ran = random.nextInt(total_words.size());
String tempString=onlySearch(total_words.get(ran), 1);
myintent.putExtra("word", total_words.get(ran));
myintent.putExtra("meaning", tempString);
myintent.putExtra("language", 1);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,101,myintent,PendingIntent.FLAG_UPDATE_CURRENT);
//NotificationTime is the sharedPreference file, in which i am storing hours and minute got from timepicker
alarmManager.cancel(pendingIntent);
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, NotificationTime.getInt("hour", 12));
calendar.set(Calendar.MINUTE, NotificationTime.getInt("min", 0));
calendar.set(Calendar.SECOND, 0);
if(calendar.before(Calendar.getInstance()))
calendar.add(Calendar.DATE,1);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY
, pendingIntent);
System.out.println("ALARM SET STATUS");
}
Alarm is first scheduling at the exact time perfectly but it does not gets repeated.
Actually I wanted to show notification daily at the specified time and I am passing a String with the intent. By default I had set to 12:00 PM but user can change its time. The first notification after setting time (or the first alarm) is working but its repetition is not working.
Please have a look, and if someone knows a better solution to show notification daily at the same specified time it would be appreciated if you tell me.
Thanks in advance
user setRepeating for Repeating Alarm
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
/* Repeating on every interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
My application schedules multiple alarms for particular times. These alarms are scheduled when the application starts. (For each day there are 5 alarms resulting in 35 alarms per week)...
I have verified through logs that these alarms are scheduled when the application starts.
The problem is when I started testing my application the 7 alarms goes off perfectly fine. However the 8th alarm doesn't fired. I have tested this scenario by keeping my device still for more than 1 day. How can I debug this behaviour and what are the possible reasons that prevent alarm for firing.
Edit:
Code for scheduling:
try {
if (info != null) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.HOUR_OF_DAY, info.getHour());
c.set(Calendar.MINUTE, info.getMinute());
c.set(Calendar.SECOND, 0);
Intent intent = new Intent(context, AlarmReceiverActivity.class);
intent.putExtra("name", info.getPrayerName());
intent.putExtra("sound", soundType);
intent.putExtra("time", formatTimeClock(context, info.getHour(), info.getMinute()));
PendingIntent pendingIntent = PendingIntent.getActivity(context, alarmId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
} catch (Exception e) {
Log.e("ALarmSchedularManager", e.getMessage());
}
How can I debug this behaviour
Use adb shell dumpsys alarm to see what your scheduled alarms are and when they are next to be invoked.
what are the possible reasons that prevent alarm for firing
Your code does not appear take into account the possibility that the time has already passed, though that may be handled outside the code snippet you show above.
Hopefully below code will help, I used the same in my app. Here the argument passed in AlarmManager class for repeating should be 24*60*60*1000
AlarmManager am = (AlarmManager) ct.getSystemService(Context.ALARM_SERVICE);
Intent intent1 = new Intent(ct, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ct, 0,intent1, PendingIntent.FLAG_CANCEL_CURRENT);
Date curr=new Date();
curr.setHours(h);
curr.setMinutes(m);
c.setTime(curr);
c.set(Calendar.SECOND, 0);
Calendar c1 = Calendar.getInstance();
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),24*60*60*1000, pendingIntent);
instead of hard code manipulation (24*60*60*1000) you can use AlarmManager.INTERVAL_DAY. Check this for different interval upto 1 day http://developer.android.com/reference/android/app/AlarmManager.html#INTERVAL_DAY
i created alarm demo . In that demo i am repeating an alarm . I have one problem in my demo . My alarm called service even if time passed . I am setting 16:08:00 time and called that alarm so it called my alarm service after passed that time.Please help me to stop this criteria.
AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(ctx.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = createPendingIntent(ctx);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pi);
CreatePendingIntent Method
private static PendingIntent createPendingIntent(Context context)
{
Intent myIntent = new Intent(context, MyAlarmService.class);
return PendingIntent.getService(context,0, myIntent, 0);
}
When setting an alarm to past time, the alarm immediately pops up.
Simply check if the current time is bigger than the alarm time. If so, add 24 hours to the alarm time and set the alarm.:
long timeToAlarm = calendar.getTimeInMillis();
if (calendar.getTimeInMillis() < System.currentTimeMillis())
{
timeToAlarm += (24*60*60*1000);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeToAlarm, 24*60*60*1000, pi);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pi);
if you used the above code the alarm repeats at the 24*60*60*1000 interval time.If you don't want to repeat the alarm then use the bellow code
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
the above code will cal the alarm only onetime.