I am using ServiceTracker in order to located registered services in our OSGi environment.
I have got this code in the Bundle Activator start method:
logger.debug("looking for MyService");
tracker = new ServiceTracker(ctx, MyService.class.getName(), null);
tracker.open();
MyService = ((MyService)tracker.getService());
if (MyService != null)
{
logger.debug("found MyService");
}
The problem is this:
- If I install and start my bundle the
service can be found and used. - If I restart OSGi completely MyService cannot be
found by my bundle (i.e. is NULL) even though that
my bundle is on status ACTIVE. - If I stop/start my bundle MyService
can be found and used again.
I don’t think the problem lies in the bundle that hosts MyService since it is clearly there and can be found again if my bundle is restarted.
It looks like my bundle loads before the one that has the dependent service in it which is why it can’t find it after a restart and can find it after I restart my bundle.
An indication to that is that if I list available services using
ServiceReference[] ref = tracker.getServiceReferences();
it finds no services after the OSGi restart but it does find MyService after I stop/start my bundle that looks for it.
I was trying to set Require-Bundle reference to the bundle that hosts MyService hoping that the OSGi framework will recognize the dependency but it didn’t help.
Any ideas…?
If you use the
ServiceTrackerfrom theBundleActivator, you effectively freeze the entire framework (so, no other bundles can be started at the same time). If the bundle that provides your service starts after the bundle with the tracker, you will not see the service. This explains why stopping and starting your bundle later on gives you your service.Now, if you want to track and use the service, I would spawn a new thread to do that, and use
waitForServicein stead ofgetService.