+

Search Tips   |   Advanced Search

Use OSGi services

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

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


Example

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

package com.ibm.foo.tracker;

import com.ibm.foo.simple.Foo;
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 );
        serviceTracker.open();
    }

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

    public void shutdown() {
        serviceTracker.close();
    }
}


Parent topic: Work with the OSGi service registry