2011年5月3日 星期二

OSGi - Listener

這邊例出簡單的OSGi Listener , 下面例出如何在Bundle組件中通過實現FrameworkListener,BundleListener and ServiceListener Interface,並使用BundleContext註冊監聽OSGi環境的各種事件:


import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;

public class Activator implements BundleActivator, FrameworkListener,
        BundleListener, ServiceListener {

    public void start(BundleContext context) throws Exception {

        //add listener 
        context.addFrameworkListener(this);
        context.addBundleListener(this);
        context.addServiceListener(this);
    }

    public void stop(BundleContext context) throws Exception {
    }

   
    //process framework event 
    public void frameworkEvent(FrameworkEvent event) {
        if ((event.getType() & FrameworkEvent.ERROR) != 0) {
            System.err.println("Framework ERROR: "   event.getBundle());
        }
    }

    //process bundle event
    public void bundleChanged(BundleEvent event) {
        if ((event.getType() & BundleEvent.STARTED) != 0) {
            System.err.println("Bundle STARTED: "   event.getBundle());
        } else if ((event.getType() & BundleEvent.STOPPED) != 0) {
            System.err.println("Bundle STOPPED: "   event.getBundle());
        }
    }

    //process service event
    public void serviceChanged(ServiceEvent event) {
        if ((event.getType() & ServiceEvent.REGISTERED) != 0) {
            System.err.println("Service REGISTERED: "
                      event.getServiceReference());
        }
    }

}

沒有留言:

張貼留言