Reputation: 278
I am writing an Eclipse plugin for a college project and need to be able to run code when the user exits and I can't find the correct Listener to enable me do this. An example of similar code is shown below where I listen for successfully completed save events and call a method when this occurs.
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();
}
}
So what I want is a Listener which will allow me to listen for exit events and call a method to run my code when this happens. I suppose I wont be able to ensure the exit is successfully completed before running the code but a 'pre-exit' Listener would work just fine. Also if someone does know of the correct Listener could they also tell me the commandId I will need for the exit event (e.g. the commandId for the save event in the above example is "org.eclipse.ui.file.save").
Thanks, Jacob
EDIT: To reply to javamonkey79's question:
I add the listener like this:
/* 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);
}
Upvotes: 4
Views: 2881
Reputation: 18900
The Activator class of your plugin contains a stop() method. The Activator is the class in your plugin that extends the Plugin class and that is referenced in the Manifest.MF at the "Bundle-Activator" tag. The OSGi documentation contains a description on the plugin lifecycle.
When the workspace is closed, all of the plugins are stopped. You can then add any clean-up code that you require in this section.
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. Interesting snippet from the 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.
The advantages of using this method instead of using a listener on the UI, is that you know that it will be called regardless of how the user leaves the workspace.
Upvotes: 5