Android: CountDownTimer vs AlarmManager - android

I have to run a piece of code every 5 minutes in my service. Will countdowntimer be killed since the app is not in foreground. If this is the case will alarmanager be better in running the code?
Thanks,
Sahil

I think especially if your code runs in a Service that an AlarmManager is the better alternative. You can use the AlarmManager to start your Service in a 5 minute interval like this:
Calendar calendar = Calendar.getInstance();
Intent intent = new Intent(context, YourService.class);
// Set action of Intent or add extras
long period = 5 * 60 * 1000; // 5 minutes
PendingIntent pendingIntent = PendingIntent.getService(context, alarmId, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), period, pendingIntent);
If you want to stop your alarm you have to use the same alarmId so it would be best if you put that id in a constant. Also note that you have to restart your alarm every time the phone reboots!

Related

AlarmManager.RTC doesn't fire if the device is already awake

In a broadcast receiver for the USER_PRESENT broadcast, I'm setting an alarm like this:
Intent intentAfterAlarmFire = new Intent(context, ActivityAfterAlarmFire.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1234567, intentAfterAlarmFire, 0);
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC, myTime, alarmIntent);
It works as expected when the user unlocks the device after the alarm time has passed, however, it doesn't fire the alarm if the user woke the device up before alarm time and kept using it until alarm time is passed.
Shouldn't the AlarmManager.RTC (non-wake-up) fire anyway if the device is already awake?
Thanks.
// It'll fire every 5 seconds, you can set your own time in place of cal.getTimeInMillis()
Calendar cal = Calendar.getInstance();
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, alarmIntent);

how to set an Ending Point for Alarm Manager

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);
}

How to trigger alarmManager's initial run after specific duration?

I need to trigger an alarmManager's first run at the start of next minute. for example, if the current time is 6:47:40 seconds, then the alarmManager's first run will trigger at 6:48:00 (i.e. 20 seconds later)
To achieve this I need to figure out how many second is left for the current minute to complete. this can be done using this:
Calendar c = Calendar.getInstance();
int secondsTillNextMinute = 60 - c.get(Calendar.SECOND);
Now How can I use this value in the alarmmanager.SetRepeating? My alarmManager looks like this.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 60000, createClockTickIntent(context));
private PendingIntent createClockTickIntent(Context context) {
Intent intent = new Intent(CLOCK_WIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
I want to use secondsTillNextMinute instead of System.currentTimeMillis() in my SetRepeating code. How do I do that? the 2nd parameter accepts only milisecond values?

In which condition set-repeat Alarm get canceled in android?

i Create application in android that schedule a alarm for every 20 minute. but they get canceled or not working after scheduled 5 or 8 times. is there any condition after that system cancel the scheduled alarm.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 20);
// Create a new PendingIntent and add it to the AlarmManager
Intent my123intent = new Intent(context, PolicyFormatDownloader.class);
my123intent.putExtra(commonGlobalVariables.IS_CALL_FROM_ALARM, true);
my123intent.putExtra(commonGlobalVariables.IS_CALL_MANUALLY, false);
PendingIntent pendingIntent = PendingIntent.getService(context, 12345,my123intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ (60 * 1000 * 20), 60 * 1000 * 20, pendingIntent);
please tell me the conditions in which alarm get cancel or clear by system.
thanks for ans in advance.
The alarm can be cleared in follwing two conditions:
On device reboot
All alarms set using an Alarm-Manager, are removed on device reboot
If you create a Pending Intent with same ID
On creation of similar PI with same ID-Value (as 12345 in this case), will overrride the previous PI.

How to Set Recurring AlarmManager to execute code daily

I am currently trying to write alarm manager that will make an alarm go off within a specified period of time, daily. First I check to see if the user has had an alarm set for that for that day:
if ((User.getReminderTime(Home.this) > 0)
&& (dt.getDate() != today.getDate() || dt.getDay() != today
.getDay())) {
AppointmentManager.setFutureAppointmentCheck(this
.getApplicationContext());
User.setLongSetting(this, "futureappts", today.getTime());
}
Then I go and set the actual alarm to go off between 12 and 12:10 of the next day:
public static void setFutureAppointmentCheck(Context con) {
AlarmManager am = (AlarmManager) con
.getSystemService(Context.ALARM_SERVICE);
Date futureDate = new Date(new Date().getTime() + 86400000);
Random generator = new Random();
futureDate.setHours(0);
futureDate.setMinutes(generator.nextInt(10));
futureDate.setSeconds(0);
Intent intent = new Intent(con, FutureAppointmentReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, futureDate.getTime(), sender);
}
Now I setup a test environment for this to go off every two minutes and it seems to be working fine, however when I deploy to an actual device, the reciever does not seem to be recieving the alarms. I thought it might be an issue with the device being asleep, so I added the power manager. But it still does not work:
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "keepAlive");
wl.acquire();
setFutureAppointments(context.getApplicationContext());
AppointmentManager.setFutureAppointmentCheck(context
.getApplicationContext());
User.setLongSetting(context.getApplicationContext(), "futureappts",
new Date().getTime());
wl.release();
Anyone see anything I am doing blatantly wrong or am I going about this incorrectly? thanks for any and all help.
I usually do something more along the lines of:
Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pi); // cancel any existing alarms
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);
This way, you don't have to worry about re-setting the AlarmManager in your Service.
I usually run this bit of code when my app starts (onResume in my main activity) and in a BroadcastReceiver that is set up to receive BOOT_COMPLETED.
I've written a guide on creating Services and using the AlarmManager, which is based on my own experience and a few tips & tricks I picked off from watching a Google I/O talk. If you're interested, you can read it here.
To answer your question below, all I can do is quote the docs:
public void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour. These alarms are more power-efficient than the strict recurrences supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' phase to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.
Your alarm's first trigger will not be before the requested time, but it might not occur for almost a full interval after that time. In addition, while the overall period of the repeating alarm will be as requested, the time between any two successive firings of the alarm may vary. If your application demands very low jitter, use setRepeating(int, long, long, PendingIntent) instead.
In conclusion, it's not very clear. The docs only say that the alarm "may vary". However, it should be important for you to know that the first trigger might not occur for almost a full interval after that time.
This is working, this will shoot alarm after every 5 seconds
private void setRecurringAlarm() {
Logger.d(IConstants.DEBUGTAG, "Setting Recurring Alarm");
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.SECOND, 5);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.cancel(recurringDownload);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), 1000 * 5, recurringDownload); //will run it after every 5 seconds.
}

Categories

Resources