HOWTO Lookup an OSGi Service
Imagine that a bundle A is advertising a scheduler service through the OSGi Service framework, and exposed as the interface IScheduler. In your bundle you wish to use this scheduler service. Rather than depending on the bundle directly (i.e. "requiring" the bundle), you should use the Service framework to lookup a reference to this service.
OSGi makes available a "ServiceTracker" which makes looking up services less verbose, as seen in the example below.
public class Activator implements BundleActivator
{
private static ServiceTracker schedulerTracker;
public void start(BundleContext context) throws Exception
{
schedulerTracker = new ServiceTracker(context, IScheduler.class.getName(), null);
schedulerTracker.open();
...
}
public void stop(BundleContext context) throws Exception
{
schedulerTracker.close();
...
}
public static IScheduler getScheduler()
{
IScheduler service = (IScheduler) schedulerTracker.getService();
if (service != null)
{
return service;
}
else
{
// handle error
}
}
}