我正在尝试为 OSGi EventAdmin 服务运行演示应用程序,但我实现的 EventHandler 无法监听 EventAdmin 发布者发布的事件:
下面是 Event Publisher 的代码,后面是 Listener(EventHandler) 的代码:
public class Publisher implements BundleActivator{
static EventAdmin eventAdmin;
ServiceReference ref;
static HashMap properties= null;
@Override
public void start(BundleContext context) throws Exception {
ref=context.getServiceReference(EventAdmin.class.getName());
if(ref==null){
System.err.println("Unable to aquire EventAdmin Ser Ref.");
}
eventAdmin=(EventAdmin) context.getService(ref);
if(eventAdmin==null){
System.err.println("unable to get service:EventAdmin");
}
properties=new HashMap();
properties.put("XYZ", "Test");
Event event = new Event("lnu/test/event/Demo", properties);
eventAdmin.postEvent(event);
System.out.println("event posted");
}
@Override
public void stop(BundleContext context) throws Exception {
// TODO Auto-generated method stub
}
}
监听器代码:
public class Listener implements BundleActivator, EventHandler {
public void start(BundleContext context) {
Dictionary d = new Hashtable();
d.put(EventConstants.EVENT_TOPIC, "lnu/test/event/Demo" );
context.registerService( EventHandler.class.getName(),
this, d );
System.out.println("event handler is registered now");
}
public void stop( BundleContext context) {}
public void handleEvent(Event event ) {
System.err.println("Event has been captured");
System.out.println("getTopic: "+event.getTopic());
System.out.println("getproperty: "+event.getProperty("XYZ"));
}
}
代码中的打印语句显示,发布者已经发布了事件,并且监听器注册到了EventHandler服务,但它仍然没有在监听器端调用handleEvent方法,不知道为什么?并且无法理解幕后发生的事情。没有运行时异常/错误。
使用的 IDE 是 Eclipse Juno Build id: 20120614-1722 with Equinox。
运行配置中包含以下目标平台捆绑包:
- org.eclipse.osgi
- org.eclipse.equinox.event
- org.eclipse.equinox.util
- org.eclipse.osgi.services
有人可以指出我缺少什么或做错了什么吗?或者,如果您有一些指向 OSGi EventAdmin 服务工作示例的链接?