阅读更多
osgi事件监听至少需要两个包,导入
(1)org.osgi.framework
(2) org.osgi.framework.hooks.bundle
主要代码如下,可行:
public class Activator implements BundleActivator,FrameworkListener,BundleListener,ServiceListener {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
//获取osgi环境中安装的所有bundle
for(Bundle bundle:bundleContext.getBundles()){
System.out.println("bundle symbolic name: " + bundle.getSymbolicName());
System.out.println("osgi.framework="+context.getProperty("osgi.framework"));
}
context.addFrameworkListener(this);
context.addBundleListener(this);
context.addServiceListener(this);
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
@Override
public void serviceChanged(ServiceEvent event) {
// TODO Auto-generated method stub
if((event.getType() & ServiceEvent.REGISTERED) != 0) {
System.err.println("Service Register: " + event.getServiceReference());
}
}
@Override
public void bundleChanged(BundleEvent event) {
// TODO Auto-generated method stub
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());
}
}
//处理框架事件
@Override
public void frameworkEvent(FrameworkEvent event) {
// TODO Auto-generated method stub
if((event.getType() & FrameworkEvent.ERROR) != 0){
System.err.println("Framework Error: " + event.getBundle());
}
}
}