gpt4 book ai didi

java - 如何在可停靠设备中使用 osgi 服务?

转载 作者:行者123 更新时间:2023-11-30 07:32:15 24 4
gpt4 key购买 nike

例如,如果我有一个通过注释用作可停靠窗口的类,我应该如何在该类中使用 osgi 服务?最好的办法是将其作为私有(private)成员字段。

最佳答案

你可以例如。使用 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);
}
}
}

还有一个开放的issue是否以及如何使用 CDI。

关于java - 如何在可停靠设备中使用 osgi 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35939379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com