Using OSGi services

Services can be registered and unregistered asynchronously at any time. Therefore, call a service for as short a time as possible. You can use the ServiceTracker class to track service availability concurrently.

About this task

If you want to track services, you can create a ServiceTracker object by using your bundle context, the interface you want, and the properties you want to match, and then open the tracker. You can query the tracker for the best match or all matches. Make sure that you do not occupy the service after you use it. You do not have to tell the tracker you are done; the tracker caches the matching services internally, and clears them as they are unregistered. When you have finished using the tracker, use the serviceTracker.close() method to close it.


The following example shows how to use a ServiceTracker object to track a service:


import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

 * Simplest use of a ServiceTracker to get a service
public class TrackingFooUser

    private ServiceTracker<Foo,Foo> serviceTracker;

    public TrackingFooUser( BundleContext bundleContext )
        serviceTracker = new ServiceTracker<Foo, Foo>( bundleContext, Foo.class, null );;

    public void doFoo() {
        Foo foo = serviceTracker.getService();
        //use foo
        //no need to return it... just don't use it for long.

    public void shutdown() {