How do I use an osgi service in a dockable?

杀马特。学长 韩版系。学妹 提交于 2020-01-03 02:51:06

问题


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.


回答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.



来源:https://stackoverflow.com/questions/35939379/how-do-i-use-an-osgi-service-in-a-dockable

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