A bundle acquires one or more imported services by simply overridding the
BaseBundleActivator inherited method
getImportedServices(). For example:
protected String[] getImportedServiceNames() {
return new String[] {
VendorService.SERVICE_NAME,
NapkinService.SERVICE_NAME
};
}
The bundle activator's activate() method will only
be called once the bundle has successfully acquired all the
services described by the getImportedServiceNames() method.
From inside the activate() method the imported services may
be accessed by calling the inherited method
getImportedSerivce(String) that takes as a parameter the name
of a service. For example:
protected void activate() {
VendorService vendor = (VendorService) getImportedService(VendorService.SERVICE_NAME);
NapkinService napkin = (NapkinService) getImportedService(NapkinService.SERVICE_NAME);
//...
}
activate() method has been called losing an
imported service because it has been unregistered from the OSGi
framework results in the bundle activator's deactivate()
method to be called. The deactivate() method is where the
bundle activator should stop using all of its imported services.
deactivate() method has been called, re-acquiring
all imported services will result in the bundle activator's
activate() method being called once more.
It is often useful to write getter methods to make accessing imported services more convenient:
private VendorService getVendorService() {
return (VendorService) getImportedService(VendorService.SERVICE_NAME);
}
private NapkinService getNapkinService() {
return (NapkinService) getImportedService(NapkinService.SERVICE_NAME);
}
Allowing the activate() method to be a simple as:
protected void activate() {
VendorService vendor = getVendorService();
NapkinService napkin = getNapkinService();
//...
}
Copyright © 2001, 2007 IBM Corporation and others. All Rights Reserved.