tags:

views:

97

answers:

1

I am just starting with OSGI programming and have come across two ways to listener for services being activated.

The first way, from an EclipseRCP book, uses ServiceReference:

String filter="(objectclass="+IModelCreator.class.getName()+")";
context.addServiceListener(this, filter);
modelCreators = Collections.synchronizedMap(
    new HashMap<ModelID, List<IModelCreator>>());
ServiceReference references[] = context.getServiceReferences(null, filter);
if(references==null) return;
for(int i=0;i<references.length;++i) {
    this.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
        references[i]));
}

The second, from internet examples, uses ServiceTracker:

ServiceTracker logReaderTracker = new ServiceTracker(context,
       org.osgi.service.log.LogReaderService.class.getName(), null);
logReaderTracker.open();
Object[] readers = logReaderTracker.getServices();
if (readers != null) {
        for (int i = 0; i < readers.length; i++) {
        LogReaderService lrs = (LogReaderService) readers[i];
        m_readers.add(lrs);
        lrs.addLogListener(m_logger);
    }
}
logReaderTracker.close();

Which one of these is the correct and/or best way of holding a register of all the services that implement a given Interface? Is there another way of accomplishing this? Why does there seem to be two ways of doing the same thing?

+2  A: 

As you already can derive form the package name org.osgi.util.tracker.ServiceTracker is ServiceTracker a utility class which (in some cases)

simplifies using services from the Framework's service registry.

In programming there are always several ways of doing things. You either can manage your ServiceReferences by yourself or if it suits you or your problem use the bundled utility class which has its use cases.

Also check this Best practices for accessing services

Some other sources which state that it most of time it is wise to use ServiceTracker

A Comparison of Eclipse Extensions and OSGi Services

OSGi Service Tracker

Getting Started with OSGi: Consuming a Service

jitter