how to unregister an OSGi service

折月煮酒 提交于 2020-06-16 04:40:10

问题


I have the following test code, which should register and than unregister a test service. I tested it in an Eclipse 4.5.2 Mail-Demo appliation. The problem is that the service is not unregisted, the second call for the service is not null.

BundleContext bundleContext = Activator.getDefault().getBundle().getBundleContext();

ServiceRegistration<ITestService> registration = bundleContext.registerService(ITestService.class, new TestService(), null);

ServiceReference<ITestService> serviceReference = bundleContext.getServiceReference(ITestService.class);
bundleContext.ungetService(serviceReference);

serviceReference = bundleContext.getServiceReference(ITestService.class);
System.out.println("should be null but is not: " + serviceReference);

This is the output I get:

should be null but is not: {unregister.osgiservice.ITestService}={service.id=172, service.bundleid=8, service.scope=singleton}

How do I unregister the service correctly?


EDIT:
Ok I found ServiceRegistration.unregister(), if I add the code below the service is unregisted. Which brings up the next question, how do I get the ServiceRegistration from another place where the service is registered?

registration.unregister();

serviceReference = bundleContext.getServiceReference(ITestService.class);
System.out.println("now the service is null: " + serviceReference);

Output:

should be null but is not: {unregister.osgiservice.ITestService}= service.id=174, service.bundleid=8, service.scope=singleton}
now the service is null: null

回答1:


ungetService just drops the particular service reference, it does not unregister the service.

registerService returns a ServiceRegistration which you can use to unregister the service:

ServiceRegistration<ITestService> reg = bundleContext.registerService(ITestService.class, new TestService(), null);

...

reg.unregister();

It is up to you to track the service registrations. Many plugins store them in the plugin Activator. It is also common to register the service in the Activator start method and unregister in the stop method.




回答2:


Despite the answer of greg above, I found this nasty workaround using internal classes:

((org.eclipse.osgi.internal.serviceregistry.ServiceReferenceImpl) serviceReference).getRegistration().unregister();

Sure this is bad, but I need a solution to get the ServiceRegistration. I can't store the ServiceRegistration on startup since I'm using Eclipse Gemini Blueprint (former Spring DM) to register my services.



来源:https://stackoverflow.com/questions/36181447/how-to-unregister-an-osgi-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!