14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Working in the Background<br />

276<br />

}<br />

alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);<br />

6. Modify the onStart method to set an Alarm rather than use a Timer to schedule the next<br />

refresh (if automated updates are enabled). Setting a new Intent with the same action will automatically<br />

cancel the previous Alarm.<br />

@Override<br />

public void onStart(Intent intent, int startId) {<br />

SharedPreferences prefs = getSharedPreferences(Preferences.USER_PREFERENCE,<br />

Activity.MODE_PRIVATE);<br />

int minMagIndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0);<br />

if (minMagIndex < 0)<br />

minMagIndex = 0;<br />

int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0);<br />

if (freqIndex < 0)<br />

freqIndex = 0;<br />

boolean autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);<br />

Resources r = getResources();<br />

int[] minMagValues = r.getIntArray(R.array.magnitude);<br />

int[] freqValues = r.getIntArray(R.array.update_freq_values);<br />

minimumMagnitude = minMagValues[minMagIndex];<br />

int updateFreq = freqValues[freqIndex];<br />

if (autoUpdate) {<br />

int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;<br />

long timeToRefresh = SystemClock.elapsedRealtime() + updateFreq*60*1000;<br />

alarms.set(alarmType, timeToRefresh, alarmIntent);<br />

}<br />

else<br />

alarms.cancel(alarmIntent);<br />

refreshEarthquakes();<br />

};<br />

7. You can now remove the updateTimer instance variable and the TimerTask instance doRefresh.<br />

Summary<br />

Services are one of the most compelling reasons to develop applications on the Android platform. In<br />

this chapter, you learned how to use these invisible application components to perform processing<br />

while your applications are hidden in the background.<br />

You were introduced to Toasts, a transient message box that lets you display information to users without<br />

stealing focus or interrupting their workfl ow.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!