| How to get BundleContext of a plugin? [message #906022] |
Fri, 31 August 2012 09:28  |
Kosala Yapa Messages: 132 Registered: September 2010 |
Senior Member |
|
|
Hi,
Can someone tell me how to get BundleContext of a plugin?
I used,
BundleContext bc=FrameworkUtil.getBundle(new com.kosala.model.src.Activator().getClass()).getBundleContext();
This gives:
Exception in thread "main" java.lang.NullPointerException.
Thanks
K
|
|
|
| Re: How to get BundleContext of a plugin? [message #906031 is a reply to message #906022] |
Fri, 31 August 2012 09:42   |
Joseph Carroll Messages: 156 Registered: May 2012 Location: Milwaukee, WI |
Senior Member |

|
|
Why do you want the bundle context?
The bundle context is the context that your bundle runs under, this is something that should NEVER be passed outside of the bundle that owns it. Rarely will I ever even pass it out of the activator. But to get it from the activator, it looks like this:
public class Activator implements BundleActivator {
static private Activator defaultInstance;
private BundleContext bundleContext;
// List any services here
// private ServiceTracker myService;
public Activator() {
defaultInstance = this;
}
public static Activator getDefault() {
return defaultInstance;
}
public void start(BundleContext context) throws Exception {
bundleContext = context;
}
public void stop(BundleContext context) throws Exception {
// Stop your services here
// if (myService != null) {
// myService.close();
// myService = null;
// }
bundleContext = null;
}
// Notice that this method is -> ONLY <- available within the package
BundleContext getBundleContext() {
return bundleContext;
}
// Retrieve and start your service here, something like:
// public MyService getMyService() {
// if (myService == null) {
// if (bundleContext == null)
// return null;
// myService = new ServiceTracker(bundleContext, MyService.class.getName(), null);
// myService.open();
// }
// return (MyService) myService.getService();
// }
}
JD
[Updated on: Fri, 31 August 2012 09:42] Report message to a moderator
|
|
|
|
|
| Re: How to get BundleContext of a plugin? [message #930676 is a reply to message #906031] |
Tue, 02 October 2012 10:29  |
David Lawrence Messages: 1 Registered: October 2012 Location: Atlanta |
Junior Member |
|
|
Joseph, I've been searching for a simple way to get a reference to the bundle context. Your solution is very straightforward, and it definitely worked.
I used your example to revise my Activator class. Then in a different (servlet) class in the same package, I obtained a reference to the BundleContext object using these two lines:
Activator activatorRef = Activator.getDefault();
BundleContext bc = activatorRef.getBundleContext();
And then was able to get a framework property as a test:
String fwOSVersion = bc.getProperty(Constants.FRAMEWORK_OS_VERSION);
Thank you!
David
|
|
|
Powered by
FUDForum. Page generated in 0.04935 seconds