Java Reference
In-Depth Information
Listing 1.4 OSGi bundle activator for our greeting implementation
package org.foo.hello;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext ctx) {
Greeting.instance = new Greeting("lifecycle");
}
public void stop(BundleContext ctx) {
Greeting.instance = null;
}
}
A bundle activator must implement a simple OSG i interface, which in this case is com-
posed of the two methods start() and stop() . At execution time, the framework
constructs an instance of this class and invokes the start() method when the bundle
is started and the stop() method when the bundle is stopped. (What we mean by
starting and stopping a bundle will become clearer in chapter 3.) Because the frame-
work uses the same activator instance while the bundle is active, you can share mem-
ber variables between the start() and stop() methods.
You may wonder what the single parameter of type BundleContext in the start()
and stop() methods is all about. This is how the bundle gets access to the OSG i frame-
work in which it's executing. From this context object, the module has access to all the
OSG i functionality for modularity, lifecycle, and services. In short, it's a fairly impor-
tant object for most bundles, but we'll defer a detailed introduction of it until later
when we discuss the lifecycle layer. The important point to take away from this exam-
ple is that bundles have a simple way to hook into their lifecycle and gain access to the
underlying OSG i framework.
Of course, it isn't sufficient to just create this bundle activator implementation;
you have to tell the framework about it. Luckily, this is simple. If you have an existing
JAR file you're converting to be a module, you must add the activator implementation
to the existing project so the class is included in the resulting JAR file. If you're creat-
ing a bundle from scratch, you need to compile the class and put the result in a JAR
file. You must also tell the OSG i framework about the bundle activator by adding
another piece of metadata to the JAR file manifest. For this section's example, you add
the following metadata to the JAR manifest:
Bundle-Activator: org.foo.hello.Activator
Import-Package: org.osgi.framework
Notice that you also need to import the org.osgi.framework package, because the
bundle activator has a dependency on it. To see this example in action, go to the
chapter01/greeting-example/lifecycle/ directory in the companion code and type
ant to build the example and java -jar main.jar to run it.
 
Search WWH ::




Custom Search