2012-11-02 18 views
1

我试图为OSGi EventAdmin服务运行演示应用程序,但我实现的EventHandler未能监听由EventAdmin发布者发布的事件:org.osgi.service.event.EventHandler无法监听由EventAdmin服务发布的事件

以下是事件发布者的代码,然后通过监听器(事件处理程序)代码:

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与Equinox。

继目标平台束被包括在运行配置:

  1. org.eclipse.osgi
  2. org.eclipse.equinox.event
  3. org.eclipse.equinox.util
  4. 有机.eclipse.osgi.services

有人能指出我失踪或做错了什么吗?或者,如果您有一些链接到OSGi EventAdmin服务的工作示例?

回答

1

我猜你的监听器包是在发布者包已经发布了事件之后被注册的。

因为这个原因,在bundle的启动方法中测试它是很容易出错的,除非你控制bundle的启动顺序。我建议对于这个简单的测试,您可以在发布者中单独启动一个线程,每隔几秒发布一个事件。听众应该在注册后开始获取它们。

+0

亲爱的@Robin感谢您的亲切帮助:) 您的猜测是正确的,我调查了它,发现在发布者发布该事件后监听器包已被注册。 非常感谢您的建议。 – Nadeem

0

确认您的监听器软件包正在导入与EventAdmin软件包相同的org.osgi.service.event软件包。您的监听器软件包可能包含org.osgi.service.event软件包,因此不会使用与EventAdmin软件包相同的org.osgi.service.event软件包。这可能是EventAdmin软件包不会调用您的EventHandler服务的原因。这可能是别的,但这是要检查的东西。

+0

尊敬的@BJ感谢您的帮助。发布者和侦听者都在导入相同的org.osgi.service.event包。然而,问题是在发布者发布事件之后监听器包正在被注册。 再次感谢您的帮助:) – Nadeem