1. The Intent
specifying the service to start (again, the easiest way is probably to specify the service class, if it’s your own service)
2. A Bundle
providing configuration data, which eventually gets passed to the service’s onStart()
method
Conversely, to stop the service, call stopService()
with the Intent
you used in the corresponding startService()
call.
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);
}
});
}
}
CHAPTER 32
Alerting Users via Notifications
Pop-up messages. Tray icons and their associated “bubble” messages. Bouncing dock icons. You are no doubt used to programs trying to get your attention, sometimes for good reason. Your phone also probably chirps at you for more than just incoming calls: low battery, alarm clocks, appointment notifications, incoming text message or email, etc.
Not surprisingly, Android has a whole framework for dealing with these sorts of things, collectively called
Types of Pestering
A service, running in the background, needs a way to let users know something of interest has occurred,