To use a local service, you need to start the service, get access to the service object, and then call methods on that service.. CHAPTER 30: Invoking a Service 286 The Ties That Bind T
Trang 1285
Chapter
Invoking a Service
Services can be used by any application component that hangs around for a reasonable
period of time This includes activities, content providers, and other services Notably, it
does not include pure broadcast receivers (i.e., intent receivers that are not part of an
activity), since those will get garbage collected immediately after each instance
processes one incoming Intent
To use a local service, you need to start the service, get access to the service object,
and then call methods on that service You can then stop the service when you are
finished with it, or perhaps let the service stop itself In this chapter, we will look at the
client side of the Service/WeatherPlus sample application The WeatherPlus activity
looks a lot like the original Weather application It’s just a web page showing a weather
forecast, as shown in Figure 30–1
Figure 30–1 The WeatherPlus service client
30
Trang 2CHAPTER 30: Invoking a Service
286
The Ties That Bind
To start a service, one approach is to simply call startService(), providing the Intent specifying the service to start (again, the easiest way is probably to specify the service class, if it’s your own service) Conversely, to stop a service started via startService(), call stopService() with the Intent you used in the corresponding startService() call Once the service is started, you need to communicate with it It could be that all the communication you need can be via the extras you package in the Intent Or, if it is a local service that offers a singleton, you can reference the singleton
However, if you implemented onBind() as shown in the previous chapter, there is a different way to get at the service: through bindService()
When an activity binds to a service, it primarily is requesting to be able to access the public API exposed by that service via the service’s binder, as returned by the service’s onBind() method When doing this, the activity can also indicate, via the
BIND_AUTO_CREATE flag, to have Android automatically start up the service if it is not already running
To use this technique with our WeatherPlus and WeatherPlusService classes, we first need to make a call to bindService() from onCreate():
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
browser=(WebView)findViewById(R.id.webkit);
bindService(new Intent(this, WeatherPlusService.class),
onService, Context.BIND_AUTO_CREATE);
}
This bindService() call refers to an onService callback object, an instance of
ServiceConnection:
private ServiceConnection onService=new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService=((WeatherPlusService.LocalBinder)rawBinder).getService();
}
public void onServiceDisconnected(ComponentName className) {
appService=null;
}
};
Our onService object will be called with onServiceConnected() as soon as the
WeatherPlusService is up and running We are given an IBinder object, which is an opaque handle representing the service We can use that to obtain the LocalBinder exposed by the WeatherPlusService, and from there to get the actual
WeatherPlusService object itself, held as a private data member:
private WeatherPlusService appService=null;
Trang 3We can then call methods on the WeatherPlusService, such as a call to get the forecast
page when needed:
private void updateForecast() {
try {
String page=appService.getForecastPage();
browser.loadDataWithBaseURL(null, page, "text/html",
"UTF-8", null);
}
catch (final Throwable t) {
goBlooey(t);
}
}
We also need to call unbindService() from onDestroy(), to release our binding to
WeatherPlusService:
@Override
public void onDestroy() {
super.onDestroy();
unbindService(onService);
}
If there are no other bound clients to the service, Android will shut down the service as
well, releasing its memory Hence, we do not need to call stopService() ourselves,
because Android handles that, if needed, as a side effect of unbinding
This is a fair bit more code than simply using a public static singleton for the service
object However, this approach is less likely to result in memory leaks
So to recap:
To have a service start running, use bindService() with
BIND_AUTO_CREATE (if you wish to communicate via the binding
mechanism) or startService()
To have a service stop running, do the inverse of what you did to start
it: unbindService() or stopService()
Another possibility for stopping a service is to have the service call stopSelf() on itself
You might do this if you use startService() to have a service begin running and do
some work on a background thread, so the service will stop itself when that background
work is completed
Catching the Lob
In the preceding chapter, you saw how the service sends a broadcast to let the
WeatherPlus activity know a change was made to the forecast based on movement
Now, you’ll see how the activity receives and uses that broadcast
Trang 4CHAPTER 30: Invoking a Service
288
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
The BroadcastReceiver, in turn, simply arranges to update the forecast:
private BroadcastReceiver receiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updateForecast();
}
};
Trang 5289
Chapter
Alerting Users via
Notifications
Pop-up messages, tray icons with their associated “bubble” messages, bouncing dock
icons, and so on—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
messages, and so on
Not surprisingly, Android has a whole framework for dealing with these sorts of alerts,
collectively called notifications, which is the subject of this chapter
Types of Pestering
A service, running in the background, needs a way to let users know something of
interest has occurred, such as when e-mail has been received Moreover, the service
may need some way to steer users to an activity where they can act on the event, such
as reading a received message For this, Android supplies status bar icons, flashing
lights, and other indicators collectively known as “notifications”
Your current phone may already have such icons, to indicate battery life, signal strength,
whether Bluetooth is enabled, and the like With Android, applications can add their own
status bar icons, with an eye toward having them appear only when needed (e.g., a
message has arrived)
In Android, you can raise notifications via the NotificationManager The
NotificationManager is a system service To use it, you need to get the service object
via getSystemService(NOTIFICATION_SERVICE) from your activity
The NotificationManager gives you three methods: one to pester (notify()) and two to
stop pestering (cancel() and cancelAll())
31
Trang 6CHAPTER 31: Alerting Users via Notifications
290
The notify() method takes a Notification, which is a data structure that spells out the form your pestering should take The capabilities of this object are described in the following sections
Hardware Notifications
You can flash LEDs on the device by setting lights to true, also specifying the color (as
an #ARGB value in ledARGB) and the pattern in which the light should blink (by providing off/on durations in milliseconds for the light via ledOnMS and ledOffMS) Note, however, that Android devices will apply best efforts to meet your color request, meaning that different devices may give you different colors, or perhaps no control over color at all For example, the Motorola CLIQ reportedly has only a white LED, so you can ask for any color you want, and you will still get white
You can play a sound, using a Uri to a piece of content held, perhaps, by a
ContentManager (sound) Think of this as a “ringtone” for your application
You can vibrate the device, controlled via a long[] indicating the on/off patterns (in milliseconds) for the vibration (vibrate) You might do this by default, or you might make
it an option the user can choose when circumstances require a more subtle notification than a ringtone To use this approach, you will need to request the VIBRATE permission (see Chapter 28 for more on permissions)
Icons
While the flashing lights, sounds, and vibrations are aimed at getting users to look at the device, icons are designed to take them the next step and tell them what’s so important
To set up an icon for a Notification, you need to set two public fields: icon, where you provide the identifier of a Drawable resource representing the icon, and contentIntent, where you supply an PendingIntent to be raised when the icon is clicked You should make sure the PendingIntent will be caught by something—perhaps your own
application code—to take appropriate steps to let the user deal with the event triggering the notification You can also supply a text blurb to appear when the icon is put on the status bar (tickerText)
If you want all three, the simpler approach is to call setLatestEventInfo(), which wraps
an icon, contentIntent, and tickerText in a single call
Seeing Pestering in Action
Let’s now take a peek at the Notifications/Notify1 sample project, in particular the NotifyDemo class:
package com.commonsware.android.notify;
import android.app.Activity;
import android.app.Notification;