EventBroker是E4平台力推的事件处理机制实现,到底这东西有什么好的,我们来看一个例子就知道了。
1、创建一个E4工程。
2、假设我们需要在E4平台启动后执行一些任务,那么增加StartupLifeCycleHandler类,并在plugin.xml添加“lifeCycleURI”属性就可以了。
<extension id="product" point="org.eclipse.core.runtime.products">
<product name="client" application="org.eclipse.e4.ui.workbench.swt.E4Application">
<property name="appName" value="client"></property>
<property name="lifeCycleURI" value="platform:/plugin/client/client.handlers.StartupLifeCycleHandler"></property>
</product>
</extension>
3、在StartupLifeCycleHandler定义事件处理机制
package e4demo.handlers;import javax.inject.Inject;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.internal.workbench.E4Workbench;
import org.eclipse.e4.ui.workbench.lifecycle.PostContextCreate;
import org.eclipse.jface.window.Window;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
@SuppressWarnings("restriction")
public class StartupLifeCycleHandler {
@Inject
IEventBroker eventBroker;
@PostContextCreate
public void startup(IEclipseContext context) {
EventHandler attListener = new EventHandler() {
@Override
public void handleEvent(Event event) {
System.out.println("event.getTopic: " + event.getTopic());
}
};
if(eventBroker != null) {
eventBroker.subscribe("hello", attListener);
}
}
}
然后通过eventBroker订阅了主题为“hello”的事件(和RSS订阅类似嘛),然后委托EventHandler处理。attListener的工作是接收到事件后将事件主题打印到控制台上。
4、在OpenHandler.java中发布”hello”事件主题
import javax.inject.Inject;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.services.events.IEventBroker;
public class OpenHandler {
@Execute
public void execute(IEventBroker eventBroker) throws Exception {
eventBroker.send("hello", null);
}
}
5、运行,点击Open按钮,你会发现控制台输出:
event.getTopic: hello