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

thread.start();<br />

}<br />

private Runnable doBackgroundThreadProcessing = new Runnable() {<br />

public void run() {<br />

backgroundThreadProcessing();<br />

}<br />

};<br />

// Method which does some processing in the background.<br />

private void backgroundThreadProcessing() {<br />

[ ... Time consuming operations ... ]<br />

handler.post(doUpdateGUI);<br />

}<br />

// Runnable that executes the update GUI method.<br />

private Runnable doUpdateGUI = new Runnable() {<br />

public void run() {<br />

updateGUI();<br />

}<br />

};<br />

private void updateGUI() {<br />

[ ... Open a dialog or modify a GUI element ... ]<br />

}<br />

The Handler class lets you delay posts or execute them at a specifi c time, using the postDelayed and<br />

postAtTime methods, respectively.<br />

In the specifi c case of actions that modify Views, the UIThreadUtilities class provides the<br />

runOnUIThread method, which lets you force a method to execute on the same thread as the specifi<br />

ed View, Activity, or Dialog.<br />

Within your application components, Notifi cations and Intents are always received and handled on the<br />

GUI thread. In all other cases, operations that explicitly interact with objects created on the GUI thread<br />

(such as Views) or that display messages (like Toasts) must be invoked on the main thread.<br />

Moving the Earthquake Service to a Background Thread<br />

The following example shows how to move the network lookup and XML processing done in the<br />

EarthquakeService onto a background thread:<br />

1. Rename the refreshEarthquakes method to doRefreshEarthquakes.<br />

private void doRefreshEarthquakes() {<br />

[ ... previous refreshEarthquakes method ... ]<br />

}<br />

2. Create a new refreshEarthquakes method. It should start a background thread that executes<br />

the newly named doRefreshEarthquakes method.<br />

private void refreshEarthquakes() {<br />

Thread updateThread = new Thread(null, backgroundRefresh,<br />

“refresh_earthquake”);<br />

updateThread.start();<br />

261

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

Saved successfully!

Ooh no, something went wrong!