2009-05-06 17 views
4

我正在爲大學項目編寫一個Eclipse插件,並且需要能夠在用戶退出時運行代碼,並且找不到正確的偵聽器來使我能夠執行此操作。下面顯示了類似代碼的示例,其中我偵聽已成功完成的保存事件,並在發生這種情況時調用方法。如何在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(); 
    } 
} 

所以,我要的是一個監聽器,這將使我聽的退出事件並調用一個方法來我的代碼運行時發生這種情況。我想我不能確保在運行代碼之前退出已成功完成,但「退出前」監聽器可以正常工作。另外如果有人確實知道正確的Listener,他們也可以告訴我commandId我需要退出事件(例如上面例子中的save事件的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); 
} 
+0

查看http://stackoverflow.com/questions/515993/what-is-the-correct-way-to-add-a-shutdown-hook-for-an-eclipse-rcp-application/671532 – Uri 2009-05-06 06:29:06

+0

所反映的我問到的問題會引發另一個問題。即如何檢測JVM是否以不規則的方式關閉。例如,由於強制操作系統關閉。 – 2009-05-07 11:47:13

回答

5

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有趣的片段:

注1:如果一個插件已經 自動啓動,這種方法 將自動被 平臺時,平臺關閉 下調用。

使用此方法而不是在UI上使用偵聽器的優點是,您知道無論用戶如何離開工作區,都會調用它。