: Beginning Android

Catching the Lob

Catching the Lob

In Chapter 31, we showed how the service sends a broadcast to let the WeatherPlus activity know a change was made to the forecast based on movement. Now, we can see how the activity receives and uses that broadcast.

Here are the implementations of onResume() and onPause() for WeatherPlus:

@Override
public voidonResume() {
super.onResume();
registerReceiver(receiver,
newIntentFilter(WeatherPlusService.BROADCAST_ACTION));
}
@Override
public voidonPause() {
super.onPause();
unregisterReceiver(receiver);
}

In onResume(), we register a static BroadcastReceiver to receive Intents matching the action declared by the service. In onPause(), we disable that BroadcastReceiver, since we will not be receiving any such Intents while paused, anyway.

The BroadcastReceiver, in turn, simply arranges to update the forecast on the UI thread:

private BroadcastReceiver receiver =newBroadcastReceiver() {
public voidonReceive(Context context, Intent intent) {
runOnUiThread(newRunnable() {
public voidrun() {
updateForecast();
}
});
}
};

And updateForecast() uses the interface stub to call into the service and retrieve the latest forecast page, also handling the case where the forecast is not yet ready (null):

private voidupdateForecast() {
try {
String page = service.getForecastPage();
if (page==null) {
browser.postDelayed(newRunnable() {
public voidrun() {
updateForecast();
}
}, 4000);
Toast
.makeText(this, "No forecast available", 2500).show();
}else {
browser.loadDataWithBaseURL(null, page, "text/html",
"UTF-8", null);
}
}catch(final Throwable t) {
svcConn.onServiceDisconnected(null);
runOnUiThread(newRunnable() {
public voidrun() {
goBlooey(t);
}
});
}
}


: 0.036. /Cache: 0 / 0