Книга: 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 void onResume() {
super.onResume();
registerReceiver(receiver,
new IntentFilter(WeatherPlusService.BROADCAST_ACTION));
}
@Override
public void onPause() {
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 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
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 void updateForecast() {
try {
String page = service.getForecastPage();
if (page==null) {
browser.postDelayed(new Runnable() {
public void run() {
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(new Runnable() {
public void run() {
goBlooey(t);
}
});
}
}
- Новые функции API для работы с Blob и массивами
- 4.4.4 The Dispatcher
- About the author
- Chapter 7. The state machine
- Appendix E. Other resources and links
- Example NAT machine in theory
- The final stage of our NAT machine
- Compiling the user-land applications
- The conntrack entries
- Untracked connections and the raw table
- Basics of the iptables command
- Other debugging tools