开发者

How to subscribe to an OpenProject event in Eclipse?

I'm developing an Eclipse plugin.

I have been reading how to subscribe get notification when a project is about to be closed, using the interface IResourceChangeListener, and using the PRE_CLOSE event type. The following text has been taken from the Eclipse help:

Notifies listeners that a project is about to be closed. This event can be used to extract and sa开发者_如何学运维ve necessary information from the in-memory representation (e.g., session properties) of a project before it is closed. (When a project is closed, the in-memory representation is disposed). The workspace is locked (no resources can be updated) during this event. The event contains the project that is being closed.

I didn't found how to be notified when a project is about to be opened.


You can create your own IResourceChangeListener and filter the kind of delta by IResourceDelta.OPEN, which only affects to IProjects, and it's fired both when opening and closing a project:

public void resourceChanged(IResourceChangeEvent event) {
    if (event == null || event.getDelta() == null)
        return;
    event.getDelta().accept(new IResourceDeltaVisitor() {
        public boolean visit(IResourceDelta delta) throws CoreException {
            if (delta.getKind() == IResourceDelta.OPEN)
                final IResource resource = delta.getResource();
                if (!(resource instanceof IProject))
                    return;
               //do your stuff and check the project is opened or closed
        }
}

Useful link: http://www.eclipse.org/articles/Article-Resource-deltas/resource-deltas.html


I know this question has been long answered, but I want to update it with a working code snippet, just in case anybody will need it. I tested it on Eclipse Luna, Indigo, and Kepler.

public void resourceChanged(final IResourceChangeEvent event) {
    if (event == null || event.getDelta() == null) {
        return;
    }

    try {
        event.getDelta().accept(new IResourceDeltaVisitor() {
            public boolean visit(final IResourceDelta delta) throws CoreException {
                IResource resource = delta.getResource();
                if (((resource.getType() & IResource.PROJECT) != 0)
                        && resource.getProject().isOpen()
                        && delta.getKind() == IResourceDelta.CHANGED
                        && ((delta.getFlags() & IResourceDelta.OPEN) != 0)) {

                    IProject project = (IProject)resource;
                    projectOpened(project);
                }
                return true;
            }
        });
    } catch (CoreException e) {
        e.printStackTrace();
    }
}


IResourceChangeEvent is POST_CHANGE and related IResourceDelta kind is IResourceDelta.CHANGED and flags include IResourceDelta.OPEN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜