Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android ApiDemos示例解析(42):App->Service->Remote Service Binding

Android ApiDemos示例解析(42):App->Service->Remote Service Binding

編輯:Android開發教程

本例和下個例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallback.aidl 及ISecondary.aidl。

Android Interface Definition Language(AIDL)和其它一些支 持遠程方法調用RMI的系統的IDL類似,它定義了Service和Client 之間的使用接口約定,這種遠程調用一般需要通過進程間通信 機制(IPC)來實現。在Android系統,一個進程(Process)通常不能直接訪問其它進程的內存空間,Android系統支持使用AIDL來 實現使用不同進程間調用服務接口。

在設計AIDL接口之前,要意識到使用AIDL接口是通過直接函數調用的方法來進行的 ,但這種遠程調用所發生的線程Thread隨調用者是否和Service提供者屬於同一進程Process的不同而不同:

如 果調用者與Service屬於同一個進程(可以稱為Local Process),那麼AIDL Call將使用與調用者同一線程執行。因此如果你的 應用只使用Local Process來訪問AIDL Call,那麼根本就無必要使用AIDL接口,使用Binder即可,參見Android ApiDemo示例解 析(39):App->Service->Local Service Binding。

如果使用Remote Process方式來調用AIDL ,Android 將會使用由本進程管理的線程池(Thread pool)來分發函數調用。因此你的Service需要能夠處理多進程觸發的AIDL Call,換句 話來說,AIDL接口的實現必須是Thread-safe的。

關鍵字oneway 可以修改遠程調用的的行為,當使用oneway關 鍵字時,remote call調用後立即返回,有點類似異步調用。

定義AIDL 接口的步驟如下:

AIDL接口定 義使用Java Interface語法定義在 .aidl文件中,然後必須同時放在Service和Client 的 src目錄下。 當使用Eclipse 編譯時 ,Android SDK工具會根據 .aidl的接口定義自動生成對應的IBinder接口定義 (定義在gen目錄下) Service必須實現由這個 IBinder接口定義。 Client然後可以通過綁定Service來訪問這些方法。

1. 創建. aidl 文件

AIDL接口定義使用 和Java Interface定義同樣的語法,每個.aidl文件只能定義一個調用接口,而且只能定義接口方法,不能含有靜態變量定義。 AIDL缺省支持 int ,long, char, boolean, String, CharSequence, List ,Map 變量類型,也可以引用其它 .aidl中定義的類 型。

下面是IRemoteService.aidl 的定義,

package com.example.android.apis.app;     
import com.example.android.apis.app.IRemoteServiceCallback;     
/**    
 * Example of defining an interface for calling on to a remote service    
 * (running in another process).    
 */ 
interface IRemoteService {     
 /**    
 * Often you want to allow a service to call back to its clients.    
 * This shows how to do so, by registering a callback interface with    
 * the service.    
 */ 
 void registerCallback(IRemoteServiceCallback cb);     
 /**    
 * Remove a previously registered callback interface.    
 */ 
 void unregisterCallback(IRemoteServiceCallback cb);<br />     
}

編譯時,Android SDK 工具自動在gen目錄下生成對應的 IRemoteService.java。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved