Java Reference
In-Depth Information
utility class to do all this for you—a class that has been battle hardened and tested in
many applications, that you can configure and customize as you require? It does, and
the class's name is ServiceTracker .
4.3.3
Tracking ser vices
The OSG i ServiceTracker class provides a safe way for you to get the benefits of service
listeners without the pain. To show how easy it can be, let's take the bundle activator
from the last example and adapt it in the following listing to use the service tracker.
Listing 4.13 Standard tracker example
public class Activator implements BundleActivator {
BundleContext m_context;
ServiceTracker m_logTracker;
public void start(BundleContext context) {
m_context = context;
m_logTracker = new ServiceTracker(context,
LogService.class.getName(), null);
m_logTracker.open();
startTestThread();
}
public void stop(BundleContext context) {
Closes
tracker
m_logTracker.close();
stopTestThread();
}
}
In this example, you use the basic ServiceTracker constructor that takes a bundle
context, the service type you want to track, and a customizer object. We'll look at cus-
tomizers in a moment; for now, you don't need any customization, so you pass null . If
you need more control over what services are tracked, there's another constructor
that accepts a filter.
NOTE Before you can use a tracker, you must open it using the open() method
to register the underlying service listener and initialize the tracked list of ser-
vices. This is often the thing people forget to do when they first use a service
tracker, and then they wonder why they don't see any services. Similarly, when
you're finished with the tracker, you must close it. Although the framework
automatically removes the service listener when the bundle stops, it's best to
explicitly call close() so that all the tracked resources can be properly cleared.
And that's all you need to do to track instances of the Log Service—you don't need to
write your own listener or worry about managing long lists of references. When you
need to use the Log Service, you ask the tracker for the current instance:
LogService logService = (LogService) m_logTracker.getService();
 
Search WWH ::




Custom Search