If I have for example a class that is used as a dockable window by annotating it, how am I supposed to use an osgi service in that class? The best would be to have it as a private member field.
            Asked
            
        
        
            Active
            
        
            Viewed 64 times
        
    1 Answers
1
            
            
        You can eg. use a ServiceTracker:
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
...
@ViewDocking(...)
public class MyView extends SomeNode{
    private final ServiceTracker<MyService, MyService> myServiceTracker;
    private MyService myService;
    public MyView(){
        BundleContext bundleContext = FrameworkUtil.getBundle(MyView.class).getBundleContext();
        myServiceTracker = new ServiceTracker<>(bundleContext, MyService.class,
                new MyServiceTrackerCustomizer(bundleContext));
        myServiceTracker.open(false);
    }
    ...
    public void setMyService(MyService myService) {
        if (this.myService != null){
           ...
        }
        this.myService = myService;
        if (this.myService != null){
           ...
        }
    }
    ...
    private class MyServiceTrackerCustomizer implements
            ServiceTrackerCustomizer<MyService, MyService> {
        private final BundleContext context;
        public MyServiceTrackerCustomizer(BundleContext context) {
            this.context = context;
        }
        @Override
        public MyService addingService(ServiceReference<MyService> reference) {
            MyService myService = context.getService(reference);
            setMyService(myService);
            return myService;
        }
        @Override
        public void modifiedService(ServiceReference<MyService> reference, MyService service) {
            addingService(reference);
            removedService(reference, service);
        }
        @Override
        public void removedService(ServiceReference<MyService> reference, MyService service) {
            setMyService(null);
            context.ungetService(reference);
        }
    }
}
There is also an open issue if and how CDI could be used.
        Puce
        
- 37,247
 - 13
 - 80
 - 152