注册服务:
BundleContext bundleContext = FrameworkUtil.getBundle(当前类.class).getBundleContext();
EventHandler eventCreateNewConfigEventHandler = new EventHandler() {
@Override
public void handleEvent(final org.osgi.service.event.Event event) {
doSomething()...
}
};
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put(EventConstants.EVENT_TOPIC, "licensecheck/check");//$NON-NLS-1$
ServiceRegistration<EventHandler> registerCheckPermissionService = bundleContext.registerService(EventHandler.class, eventCreateNewConfigEventHandler, properties);
发通知:
BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
ServiceReference<EventAdmin> serviceRef = bundleContext.getServiceReference(EventAdmin.class);
EventAdmin eventAdmin = bundleContext.getService(serviceRef);
final Map<String, String> properties = new HashMap<String, String>();
org.osgi.service.event.Event event = new org.osgi.service.event.Event("licensecheck/check", properties);
eventAdmin.sendEvent(event);
如果想接到通知做什么事,可以在那个地方初注册服务,然后在另一个插件中发消息,注意,event的内容要相同,注册的服务才能收到发的通知,如例程中的licensecheck/check
发送这个通知后,服务就可以收到通知,并在handleEvent
方法中处理,handleEvent
方法的event 可以获取到发送通知时的event 带的属性 properties
注意:注册服务不能注册多次,注册服务的代码不能被执行多次,否则发一个通知过来,会收到多次,即handleEvent
方法会被执行多次,最好是在注册服务之前先判断一下registerCheckPermissionService
是否为空,如果不为空,调用registerCheckPermissionService.unregister()
注销服务后,再注册