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 />

258<br />

}<br />

@Override<br />

public void onPause() {<br />

earthquakeCursor.deactivate();<br />

super.onPause();<br />

}<br />

public class EarthquakeReceiver extends BroadcastReceiver {<br />

@Override<br />

public void onReceive(Context context, Intent intent) {<br />

earthquakeCursor.requery();<br />

MapView earthquakeMap = (MapView)findViewById(R.id.map_view);<br />

earthquakeMap.invalidate();<br />

}<br />

}<br />

Now when the Earthquake Activity is launched, it will start the Earthquake Service. This Service will<br />

then continue to run, updating the earthquake Content Provider in the background, even after the<br />

Activity is suspended or closed.<br />

You’ll continue to upgrade and enhance the Earthquake Service throughout the chapter, fi rst using<br />

Toasts and later Notifi cations.<br />

At this stage, the earthquake processing is done in a Service, but it’s still being executed on the main thread.<br />

Later in this chapter, you’ll learn how to move time-consuming operations onto background threads to<br />

improve performance and avoid “<strong>Application</strong> Unresponsive” messages.<br />

Binding Activities to Services<br />

When an Activity is bound to a Service, it maintains a reference to the Service instance itself, allowing<br />

you to make method calls on the running Service as you would any other instantiated class.<br />

Binding is available for Activities that would benefi t from a more detailed interface with a Service. To<br />

support binding for a Service, implement the onBind method as shown in the simple example below:<br />

private final IBinder binder = new MyBinder();<br />

@Override<br />

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

return binder;<br />

}<br />

public class MyBinder extends Binder {<br />

MyService getService() {<br />

return MyService.this;<br />

}<br />

}<br />

The connection between the Service and Activity is represented as a ServiceConnection.<br />

You’ll need to implement a new ServiceConnection, overriding the onServiceConnected

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

Saved successfully!

Ooh no, something went wrong!