Java – when to use servicetracker and servicereference

I've just started using OSGi programming, and I've encountered two ways to listen to activated services

The first method is to use servicereference from eclipse RCP books:

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]));
}

Second, from the example of the Internet, use 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 is the right and / or best way to hold the registry of all services that implement a given interface? Is there another way to implement it? Why do two seem to do the same thing?

Solution

Because you can already start from the package name org osgi. util. tracker. Servicetracker gets the form, which is a utility class (in some cases)

There are always several ways to do things in programming You can manage your servicereferences yourself, or use a bundled utility class with its use cases for you or your problems

Also check the best practices for accessing services

Some other sources say it is wise to use servicetracker most of the time

A Comparison of Eclipse Extensions and OSGi Services

OSGi Service Tracker

Getting Started with OSGi: Consuming a Service

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>