android插件化-apkplug中OSGI服务基本原理-08

咱们提供 apkplug 下OSGI使用demo 源码托管地址为 http://git.oschina.net/plug/OSGIService java

一 OSGI与android Service 异同点    android

    OSGI服务与android Service概念差很少也是Service ,Client 关系。 git

    android Service接口  --service.AIDL     spa

    OSGI接口                --java interface .net

    因此android 进程间通讯Service只能传递序列化过的数据 而OSGI服务能够传递任何java对象。 插件

 

二 OSGI与android Service注册/查询方式对比 code

    1.服务注册 对象

        android Service            接口

Intent intent=new Intent(Context,Service.class);
Context.startService(intent);

        OSGI Service        进程


BundleContext context;      //插件上下文
ServiceRegistration m_reg = context.registerService(
    sayHelloImp.class.getName(),//服务名称  通常为接口类名
     my,                         //服务具体实现类
     null);

2.服务查询

        android Service     

Intent intent=new Intent(Context,Service.class);
Context.bindService(intent, new ServiceConnection())
...

       OSGI Service    


//利用插件上下文BundleContext查询服务
 ServiceReference ref  =  context.getServiceReference(Service.class.getName());
        if  (ref  !=   null ) {
        	//查找到服务
        	Service service  =  (Service) context.getService(ref);
        	 if  (service  !=   null ) {
        	          //调用服务接口
        		 service.sayHello(imp); 
        	 }
        	 //注销服务
        	 context.ungetService(ref);
        }


三    OSGI服务特色

        OSGI服务是暂态的插件可能随时被关闭或卸载,因此咱们每次在使用服务的时候都最好先查询服务是否还存在。

四    OSGI服务注意事项

       使用OSGI服务时应注意服务接口java类的一致性,服务者与消费者应使用相同的java接口(类加载器相同),不然可能出现服务查询时类型强制转换异常。通常状况下咱们以服务者提供java接口

相关文章
相关标签/搜索