obtaining a reference to EventAdmin too complex [message #513492] |
Wed, 10 February 2010 07:01  |
Eclipse User |
|
|
|
Currently, to obtain the EventAdmin, you would have to do something similar to this if you would not cache the reference somewhere:
ServiceReference ref = null;
BundleContext ctx = null;
EventAdmin ea = null;
{
Bundle b = FrameworkUtil.getBundle( this.getClass() );
if ( b != null ) {
ctx = b.getBundleContext();
if ( ctx != null ) {
ref = ctx.getServiceReference( EventAdmin.class.getName() );
if ( ref != null ) {
ea = (EventAdmin) ref;
}
}
}
}
if ( ea != null ) {
Map<String, Object> props = new HashMap<String, Object>();
// add event props...
ea.sendEvent( new Event( "com.example.myEvents/doSomething", props ) );
ctx.ungetService( ref );
}
Are there any simpler ways to get the EventAdmin?
I mean just a one-liner like this:
boolean sent = SomeEventUtil.sendEvent( new Event(...) );
or even this:
boolean sent = SomeEventUtil.sendEvent( topic, props );
|
|
|
Re: obtaining a reference to EventAdmin too complex [message #513606 is a reply to message #513492] |
Wed, 10 February 2010 11:48  |
Eclipse User |
|
|
|
You should look at using ServiceTracker to track the service or Declarative Services to inject the service.
For ServiceTracker it would be something like this:
ServiceTracker eventAdminTracker =
new ServiceTracker(context, EventAdmin.class.getName(), null);
eventAdminTracker.open();
....
EventAdmin eventAdmin = (EventAdmin) eventAdminTracker.getService();
if (eventAdmin != null) {
// do your stuff here
}
If using a ServiceTracker then you should create and open it when your bundle is activated. Then you can use the tracker throughout your code to obtain the EventAdmin service.
HTH.
Tom.
|
|
|
Powered by
FUDForum. Page generated in 0.07094 seconds