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接口

相關文章
相關標籤/搜索