我们在Android(2.1)上成功运行Apache Felix 4.0.3,可以在运行时部署/删除Bundles。对于OSGI Bundles之间的依赖管理,我们使用Felix DependenyManager。
现在我们要将运行OSGI Bundles的数据发送到Android GUI并显示它。
我们如何完成这项任务?我们可以使用某种回调吗?
答案 0 :(得分:2)
假设通过“发送数据”表示与捆绑提供的服务进行交互,没有什么特别之处:只需确保持有BundleContext
实例的Felix
实例给你,并用它来请求服务。绑定数据的方式完全取决于您,就像在任何其他Java项目中一样。
作为一个相当人为的例子,你可以做类似
的事情Map<String, Object> config = new HashMap<String, Object>();
/// make settings here, including providing the bundles to start
Felix felix = new Felix(config);
felix.start();
BundleContext context = felix.getBundleContext();
// now get some service! Remember to do nullchecks.
ServiceReference<PackageAdmin> ref = context.getServiceReference(PackageAdmin.class);
PackageAdmin admin = context.getService(ref);
ExportedPackage[] exportedPackages = admin.getExportedPackages(felix);
// use the result to update your UI
TextView field = (TextView) findViewById(R.id.textfield);
field.setText(exportedPackages[0].getName());
设置框架,获取一些服务,并使用一些数据更新UI。
没有可以使用的默认回调,但我特别喜欢的一个技巧是让UI元素知道他们的OSGi环境;通过这种方式,您可以让他们“监听”框架中的更改。下面是我使用的简化视图,我更喜欢将复杂的内容委托给Apache Felix Dependency Manager。
例如,假设你有一些监听器接口。
public interface ClockListener {
public void timeChanged(String newTime);
}
并且您有一些服务会定期调用使用当前时间实现此接口的所有服务。您现在可以创建一个TextField
,每次调用此方法时它都会自动更新。像,
public class ClockTextField extends TextView implements ClockListener {
public ClockTextField(Context context) {
super(context);
}
public void timeChanged(String newTime) {
setText(newTime);
}
public void register(BundleContext bundleContext) {
// remember to hold on to the service registration, so you can pull the service later.
// Better yet, think about using a dependency management tool.
bundleContext.registerService(ClockListener.class, this, null);
}
}