Android remote service : how to bind

Android remote service : how to bind ?


使用遠程調用需要用aidl 文件,此文件定義遠程服務和應用程序通信的接口,經過編譯會自動生成相應的.java文件,
結合android apidemo 中remote service binding app 步奏如下:


1. 應用程序的Activity請求remote service 連接
與本地服務調用一樣通過bindservice()綁定到遠程服務上,bindservice第一個參數是intent,用來運行遠程服務,
注意:需要同時在manefest 文件中聲明相應的 remote service 並在intent-felter聲明service的aidl文件,


2. service 啓動,依次調用service的onCreate() onBind()方法,onCreate()會以通知消息的形式告知服務已經生成,
onBind()返回用於處理Bind IPC 的Binder 對象給系統。服務的綁定對象Binlder是由xxx.aidl對應的.java 文件的xxxx.stub類生成,
並在其中實現aidi文件中定義的方法。
xxx.Stub myBinder = new xxx.Stub(){
public function(){
......
}
};


3. Activity 生成執行服務與Binder IPC 的代理對象
調用onServiceConnected()傳遞binder給xxx.Stub.asInterface() 生成與remoteservice服務綁定在一起的服務代理對象 xxx.Stub.Proxy 保存在mService中

ServiceConnetion(){
public void onServiceConnected(ComponentName classname, IBinder service){
mService = xxx.Stub.asInterface(service);
}
}

至此步,remoteservice 與aidl接口的綁定完成,應用程序的activity可以調用。


4.應用程序的activity使用代理服務對象調用remoteservice 的代理方法
mService.function()

5. Binder IPC : xxx.Stub.Proxy 向xxx.Stub傳遞Binder IPC 數據


6. remoteservice 服務: 調用其function()方法
發佈了30 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章