Alarms provide a middle-ground alternative to the polling and Intent-based techniques described so far.
Alarms, covered in detail in Chapter 9, provide a flexible way to schedule regular events within your application. Using alarms you can poll at regular intervals, using an Intent to trigger your updates.
Using Alarms to refresh your widgets is similar to using the Intent-driven model described earlier. Add a new Intent Filter to the manifest entry for your widget and override its onReceive method to identify the Intent that triggered it. Within your application, use the Alarm Manager to create an Alarm that fires an Intent with the registered action.
Alarms have an advantage over the minimum refresh rate, thanks to their flexibility.
Like the widgets' refresh rate, Alarms also have the ability to wake the device when they fire — making it equally important to take care to minimize battery use.
Alternatively, by using the rtc or elapsed_realtime modes when constructing your alarm, you can configure it to trigger after a minimum interval has elapsed, but only after the device has awakened:
AlarmManager.INTERVAL_HOUR, AlarmManager.INTERVAL_HOUR, pi);
Using this technique will ensure your widget is up to date when visible, without draining the battery unnecessarily to update the widget when the screen is off.
If your widget does need to be updated even when the device is on standby, you can optimize this process with the inexact repeating option, shown here:
String alarmService = Context.ALARM_SERVICE;
AlarmManager alarmManager = (AlarmManager)getSystemService(alarmService);
Intent intent = new Intent(MyAppWidget.FORCE_WIDGET_UPDATE); PendingIntent pi = PendingIntent.getBroadcast(this,
AlarmManager.INTERVAL_HALF_DAY, AlarmManager.INTERVAL_HALF_DAY, pi);
As described in Chapter 9, the inexact repeating Alarm will optimize the alarm triggers by phase-shifting all the alarms scheduled to occur at similar times. This ensures the device is only awakened once, rather than several times within a few minutes.
Was this article helpful?
Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.