Using Repeating Alarms to Update Earthquakes

Write App Reviews

Build your own Android App Dev Empire

Get Instant Access

In this final modification to the Earthquake example you'll use Alarms to replace the Timer currently used to schedule Earthquake network refreshes.

One of the most significant advantages of this approach is that it allows the Service to stop itself when it has completed a refresh, freeing significant system resources.

1. Start by creating a new EarthquakeAlarmReceiver class that extends BroadcastReceiver. package com.paad.earthquake;

import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent;

public class EarthquakeAlarmReceiver extends BroadcastReceiver { }

2. Override the onReceive method to explicitly start the EarthquakeService. @Override public void onReceive(Context context, Intent intent) {

Intent startIntent = new Intent(context, EarthquakeService.class); context.startService(startIntent);

3. Create a new public static String to define the action that will be used to trigger the Broadcast Receiver.

public static final String ACTION_REFRESH_EARTHQUAKE_ALARM = "com.paad.earthquake.ACTION_REFRESH_EARTHQUAKE_ALARM";

4. Add the new EarthquakeAlarmReceiver to the manifest, including an <intent-filter> tag that listens for the action defined in Step 3.

<receiver android:name=".EarthquakeAlarmReceiver"> <intent-filter> <action android:name="com.paad.earthquake.ACTION_REFRESH_EARTHQUAKE_ALARM"

</intent-filter> </receiver>

5. Within the EarthquakeService, update the onCreate method to get a reference to the AlarmManager, and create a new Pendinglntent that will be fired when the Alarm goes off. You can also remove the timerTask initialization.

AlarmManager alarms; PendingIntent alarmIntent;

©Override public void onCreate() {

int icon = R.drawable.icon;

String tickerText = "New Earthquake Detected"; long when = System.currentTimeMillis();

newEarthquakeNotification =

new Notification(icon, tickerText, when);

alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);


EarthquakeAlarmReceiver.ACTION_REFRESH_EARTHQUAKE_ALARM; Intent intentToFire = new Intent(ALARM_ACTION); alarmIntent =

PendingIntent.getBroadcast(this, 0, intentToFire, 0);

6. Modify the onStartCommand method to set a repeating Alarm rather than use a Timer to schedule the refreshes (if automated updates are enabled). Setting a new Intent with the same action will automatically cancel any previous Alarms.

Take this opportunity to modify the return result. Rather than setting the Service to sticky, return Service.START_NOT_STiCKY. In Step 7 you will stop the Service when the background refresh is complete; the use of alarms guarantees that another refresh will occur at the specified update frequency, so there's no need for the system to restart the Service if it is killed mid-refresh.

©Override public int onStartCommand(Intent intent, int flags, int startId) { SharedPreferences prefs =

getSharedPreferences(Preferences.USER_PREFERENCE, Activity.MODE_PRIVATE);

int minMaglndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0); if (minMaglndex < 0) minMaglndex = 0;

int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0); if (freqIndex < 0) freqIndex = 0;

boolean autoUpdate =

prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);

Resources r = getResources();

int[] minMagValues = r.getlntArray(R.array.magnitude); int[] freqValues = r.getIntArray(R.array.update_freq_values);

minimumMagnitude = minMagValues[minMagIndex]; int updateFreq = freqValues[freqIndex];

if (autoUpdate) {

int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timeToRefresh = SystemClock.elapsedRealtime() +

updateFreq*60*1000; alarms.setRepeating(alarmType, timeToRefresh, updateFreq*60*1000, alarmlntent);

else alarms.cancel(alarmlntent);


return Service.START_NOT_STICKY;

7. In the EarthquakeLookupTask, fill in the onPostExecute stub to call stopSelf when the background refresh has completed. Because the asynchronous lookup task is called only from within onStartCommand, and only if not already running, this ensures the Service is never prematurely terminated.

@Override protected void onPostExecute(Void result) { stopSelf();

8. Remove the updateTimer instance variable and the Timer Task instance doRefresh.

All code snippets in this example are part of the Chapter 9 Earthquake 4 project, available for download at


Background Services are one of the most compelling reasons to develop applications on the Android platform, but using them introduces several complexities to your applications. In this chapter you learned how to use these invisible application components to perform processing while your applications are running in the background.

You were introduced to Toasts, transient message boxes that let you display information to users without stealing focus or interrupting their workflow.

You used the Notification Manager to send alerts to your users from within Services and Activities, using customized LEDs, vibration patterns, and audio files to convey detailed event information. You learned how (and when) to create ongoing Notifications and how to customize their extended status window Layouts.

Using Alarms, you were able to schedule one-off and repeating events that broadcast Intents or started Services.

This chapter also demonstrated how to:

> Bind a Service to an Activity to make use of a more detailed, structured interface than the simple Intent extras.

> Ensure that your applications remain responsive by moving time-consuming processing like network lookups onto worker threads using AsyncTask.

> Use handlers to synchronize child threads with the main application GUI when performing operations using visual controls and Toasts.

In Chapter 10 you'll learn how to integrate your application into the home screen. Starting with creating dynamic, interactive home screen widgets you'll move on to creating Live Folders and Live Wallpapers. Finally you'll be introduced to the Quick Search Box, and learn how to surface your application's search results to the home screen search widget.

Was this article helpful?

0 0
Mobile Apps Made Easy

Mobile Apps Made Easy

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.

Get My Free Training Guide

Post a comment