您的位置:首页 > 移动开发 > Android开发

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

2014-05-15 17:27 417 查看
我们提供 apkplug 下OSGI使用demo 源码托管地址为 http://git.oschina.net/plug/OSGIService

一 OSGI与android Service 异同点   

    OSGI服务与android Service概念差不多也是Service ,Client 关系。

    android Service接口  --service.AIDL    

    OSGI接口                --java interface

    所以android 进程间通信Service只能传递序列化过的数据 而OSGI服务可以传递任何java对象。




 

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

    1.服务注册

        android Service           

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

1
BundleContext
context;      
//插件上下文
2
ServiceRegistration
m_reg = context.registerService(
3
    
sayHelloImp.
class
.getName(),
//服务名称 
一般为接口类名
4
     
my,                         
//服务具体实现类
5
     
null
);
2.服务查询

        android Service     

1
Intent
intent=
new
 
Intent(Context,Service.
class
);
2
Context.bindService(intent, 
new
 
ServiceConnection())
3
...
       OSGI Service    

01
//利用插件上下文BundleContext查询服务
02
 
ServiceReference
ref  =  context.getServiceReference(Service.
class
.getName());
03
        
if
  
(ref 
!=   
null
 
)
{
04
            
//查找到服务
05
            
Service
service  =  (Service) context.getService(ref);
06
             
if
  
(service 
!=   
null
 
)
{
07
                      
//调用服务接口
08
                 
service.sayHello(imp);
09
             
}
10
             
//注销服务
11
             
context.ungetService(ref);
12
        
}
三    OSGI服务特点

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

四    OSGI服务注意事项

       使用OSGI服务时应注意服务接口java类的一致性,服务者与消费者应使用相同的java接口(类加载器相同),否则可能出现服务查询时类型强制转换异常。一般情况下我们以服务者提供java接口
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息