r2 - 07 Jun 2007 - 22:22:55 - BrettWooldridgeYou are here: TWiki >  Developer Web  > HowtoLookupOsgi

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
      }
   }
}
Edit | WYSIWYG | Attach | Printable | Raw View | Backlinks: Web, All Webs | History: r2 < r1 | More topic actions
Developer.HowtoLookupOsgi moved from Main.HowtoLookupOsgi on 07 Jun 2007 - 22:22 by BrettWooldridge - put it back
 
Powered by TWiki
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback