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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8: Working in the Background<br />

252<br />

// Stop a service explicitly.<br />

try {<br />

Class serviceClass = Class.forName(service.getClassName());<br />

stopService(new Intent(this, serviceClass));<br />

} catch (ClassNotFoundException e) {}<br />

If startService is called on a Service that’s already running, the Service’s onStart method will be<br />

executed again. Calls to startService do not nest, so a single call to stopService will terminate it no<br />

matter how many times startService has been called.<br />

An Earthquake Monitoring Service Example<br />

In this chapter, you’ll modify the Earthquake example you started in Chapter 5 (and continued to<br />

enhance in Chapters 6 and 7). In this example, you’ll move the earthquake updating and processing<br />

functionality into a separate Service component.<br />

Later in this chapter, you’ll build additional functionality within this Service, starting by moving the<br />

network lookup and XML parsing to a background thread. Later, you’ll use Toasts and Notifi cations to<br />

alert users of new earthquakes.<br />

1. Start by creating a new EarthquakeService that extends Service.<br />

package com.paad.earthquake;<br />

import android.app.Service;<br />

import android.content.Intent;<br />

import android.os.IBinder;<br />

import java.util.Timer;<br />

import java.util.TimerTask;<br />

public class EarthquakeService extends Service {<br />

}<br />

@Override<br />

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

// TODO: Actions to perform when service is started.<br />

}<br />

@Override<br />

public void onCreate() {<br />

// TODO: Initialize variables, get references to GUI objects<br />

}<br />

@Override<br />

public IBinder onBind(Intent intent) {<br />

return null;<br />

}<br />

2. Add this new Service to the manifest by adding a new service tag within the application node.<br />

<br />

3. Move the refreshEarthquakes and addNewQuake methods out of the Earthquake Activity<br />

and into the EarthquakeService.

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

Saved successfully!

Ooh no, something went wrong!