我正在为大学项目编写一个 Eclipse 插件,需要能够在用户退出时运行代码,但我找不到正确的监听器来支持我执行此操作。下面显示了一个类似代码的示例,我在其中监听成功完成的保存事件并在发生这种情况时调用方法。
public class ExecutionListener implements IExecutionListener{
private DataCollector dataCollector;
public ExecutionListener(DataCollector dataCollector)
{
this.dataCollector = dataCollector;
}
public void postExecuteSuccess(String action, Object arg1)
{
if (action.equals("org.eclipse.ui.file.save")) {
dataCollector.writeDatabase();
}
}
所以我想要的是一个监听器,它允许我监听退出事件并在发生这种情况时调用一个方法来运行我的代码。我想我无法确保在运行代码之前成功完成退出,但是“退出前”监听器可以正常工作。此外,如果有人确实知道正确的监听器,他们是否也可以告诉我退出事件所需的 commandId(例如,上例中保存事件的 commandId 是“org.eclipse.ui.file.save”)。
谢谢,雅各布
编辑:回复 javamonkey79 的问题:
我这样添加监听器:
/* Adds a listener to listen for file save events if needed. */
if (executionListener == null) {
ICommandService service = (ICommandService) Activator.getDefault().getWorkbench().
getService(ICommandService.class);
executionListener = new ExecutionListener();
service.addExecutionListener(executionListener);
}
最佳答案
插件的 Activator 类包含一个 stop() 方法。 Activator 是插件中扩展 Plugin 类的类,在 Manifest.MF 中的“Bundle-Activator”标签中被引用。 The OSGi documentation contains a description on the plugin lifecycle.
当工作区关闭时,所有插件都将停止。然后,您可以在此部分中添加所需的任何清理代码。
public void stop(BundleContext context) throws Exception {
plugin = null;
// Code to clean up here...
super.stop(context);
}
The API describes when this method is called . API 中有趣的片段:
Note 1: If a plug-in has been automatically started, this method will be automatically invoked by the platform when the platform is shut down.
使用此方法而不是在 UI 上使用监听器的优点是,您知道无论用户如何离开工作区,它都会被调用。
关于java - 如何在我的 Eclipse 插件中监听用户退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/828248/