Java Reference
In-Depth Information
public BundleTracker(BundleContext context) {
m_context = context;
m_listener = new SynchronousBundleListener() {
public void bundleChanged(BundleEvent evt) {
synchronized (BundleTracker.this) {
if (!m_open) {
return;
}
if (evt.getType() == BundleEvent.STARTED) {
if (!m_bundleSet.contains(evt.getBundle())) {
m_bundleSet.add(evt.getBundle());
addedBundle(evt.getBundle());
}
} else if (evt.getType() == BundleEvent.STOPPING) {
if (m_bundleSet.contains(evt.getBundle())) {
m_bundleSet.remove(evt.getBundle());
removedBundle(evt.getBundle());
}
}
}
}
};
}
The bundle tracker is constructed with a
BundleContext
object, which is used to listen
for bundle lifecycle events. The tracker uses a
SynchronousBundleListener
to listen
to events because a regular
BundleListener
doesn't get notified when a bundle enters
the
STOPPING
state, only
STOPPED
. You need to react on the
STOPPING
event instead of
the
STOPPED
event because it's still possible to use the stopping bundle, which hasn't
been stopped yet; a potential subclass might need to do this if it needed to access the
stopping bundle's
BundleContext
object. The bundle listener's single method
B
makes sure the tracker is tracking bundles
C
. If so, for started events, it adds the asso-
ciated bundle to its bundle list
D
and invokes the abstract
addedBundle()
method.
Likewise, for stopping events, it removes the bundle from its bundle list and invokes
the abstract
removedBundle()
method.
The following listing shows the next portion of the
BundleTracker
.
B
Implements bundler
listener's method
Checks if tracking
bundles
C
Adds bundle
to list
D
Listing 3.15 Opening and using a
BundleTracker
public synchronized void open() {
if (!m_open) {
m_open = true;
m_context.addBundleListener(m_listener);
Bundle[] bundles = m_context.getBundles();
for (int i = 0; i < bundles.length; i++) {
if (bundles[i].getState() == ACTIVE) {
m_bundleSet.add(bundles[i]);
addedBundles(bundles[i]);
}
}
}