編輯:Android 開發實例
前言
本章內容為開發者指南(Dev Guide)/Developing/Tools/aidl,版本為 Android 2.3 r1,翻譯整理自「移動雲_文斌」。
原文:https://developer.android.com/guide/developing/tools/aidl.html(注意:3.0 r1 以後移至 Appendix 之下)
正文
由於每個應用程式都運行在各自的行程空間,且常需在不同行程之間傳遞物件,跨行程溝通便成了必要。在 Android 平台上,一個行程通常無法直接存取另一個行程的記憶體空間,因此要對話,就必須把物件拆解成作業系統能理解的基礎單元,並有序地跨越行程邊界。
以程式碼手動實作這個傳輸過程既冗長又乏味,於是 Android 提供了 AIDL 工具來處理這項工作。
AIDL(Android Interface Definition Language)是一種 IDL 語言,用於產生可在 Android 設備上兩個行程間進行行程間通訊(IPC)的程式碼。若你在一個行程中(例如 Activity)要呼叫另一個行程中(例如 Service)物件的方法,就能用 AIDL 產生可序列化的參數。
AIDL 的 IPC 機制是面向介面的,類似 COM 或 CORBA,但更為輕量。它使用代理類別在用戶端與實作端之間傳遞資料。
使用 AIDL 實作 IPC 服務的步驟如下:
AIDL 以簡潔語法宣告介面,描述其方法以及方法的參數與回傳值。這些型別可以是任何型別,甚至其他 AIDL 產生的介面。重點是:所有非內定型別都必須 import,即使它們與介面位於同一個套件。AIDL 支援的資料型別如下:
AIDL 會產生與 .aidl 同名的介面。若使用 Eclipse 外掛,AIDL 會作為編譯流程的一環自動執行;若沒有外掛,則需先手動執行 AIDL。產生的介面包含一個名為 Stub 的抽象內部類,宣告了所有 .aidl 中描述的方法,並定義了少量輔助方法,尤其是 asInterface()——它能取得 IBinder(當 applicationContext.bindService() 成功後傳到用戶端 onServiceConnected() 的那個),並回傳可用於呼叫 IPC 方法的介面實例。
要實作自己的介面,就從 YourInterface.Stub 繼承並實作相關方法(你可以先建立 .aidl 再實作 Stub 方法,無須在中間手動編譯,因為 Android 編譯流程會在 .java 之前先處理 .aidl)。
實作介面時有幾點說明:
完成介面實作後,就需要向用戶端公開它,也就是發布服務:繼承 Service,並實作 onBind(Intent) 回傳一個實作了介面的類別物件。以下程式片段示範如何把 IRemoteService 介面公開給用戶端。
public class RemoteService extends Service {
...
@Override
public IBinder onBind(Intent intent) {
// 依 action 選擇要回傳的介面
if (IRemoteService.class.getName().equals(intent.getAction())) {
return mBinder;
}
if (ISecondary.class.getName().equals(intent.getAction())) {
return mSecondaryBinder;
}
return null;
}
// 透過 IDL 定義的 IRemoteInterface
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public void registerCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.register(cb);
}
public void unregisterCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.unregister(cb);
}
};
// 服務的第二個介面
private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
public int getPid() {
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
}
};
}
若某個類別想能透過 AIDL 在行程之間傳遞,必須確保它在 IPC 兩端都有效,常見情境是與一個已啟動的服務通訊。讓類別支援 Parcelable 的四個步驟如下:
以下示範如何讓 Rect 類別實作 Parcelable:
import android.os.Parcel;
import android.os.Parcelable;
public final class Rect implements Parcelable {
public int left;
public int top;
public int right;
public int bottom;
public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect>() {
public Rect createFromParcel(Parcel in) {
return new Rect(in);
}
public Rect[] newArray(int size) {
return new Rect[size];
}
};
public Rect() {}
private Rect(Parcel in) {
readFromParcel(in);
}
public void writeToParcel(Parcel out) {
out.writeInt(left);
out.writeInt(top);
out.writeInt(right);
out.writeInt(bottom);
}
public void readFromParcel(Parcel in) {
left = in.readInt();
top = in.readInt();
right = in.readInt();
bottom = in.readInt();
}
}
警告:別忘了對從其他行程接收到的資料進行安全檢查。在上例中,rect 會從 Parcel 讀取四個數值,需確認無論呼叫方想做什麼,這些數值都在可接受範圍內。更多關於應用程式安全的內容,請參見 Security and Permissions。
呼叫遠端介面的步驟如下:
幾個呼叫 IPC 服務的提示:物件在行程間以參考計數管理;可以傳送匿名物件作為方法參數。以下程式碼示範如何呼叫 AIDL 建立的服務(完整範例可於 ApiDemos 專案取得)。
public static class Binding extends Activity {
/** 我們將在服務上呼叫的主要介面 */
IRemoteService mService = null;
/** 服務上的另一個介面 */
ISecondary mSecondaryService = null;
Button mKillButton;
TextView mCallbackText;
private boolean mIsBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_service_binding);
// 監聽按鈕點擊
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
mKillButton = (Button)findViewById(R.id.kill);
mKillButton.setOnClickListener(mKillListener);
mKillButton.setEnabled(false);
mCallbackText = (TextView)findViewById(R.id.callback);
mCallbackText.setText("Not attached.");
}
/** 與服務主要介面互動的連線類別 */
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// 連線建立後呼叫,透過 IDL 介面取得用戶端代理
mService = IRemoteService.Stub.asInterface(service);
mKillButton.setEnabled(true);
mCallbackText.setText("Attached.");
// 只要連著就想監聽服務
try {
mService.registerCallback(mCallback);
} catch (RemoteException e) {
// 若服務在連上前就崩潰,稍後會自動斷線(可能重連),無需處理
}
Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// 服務行程意外崩潰時呼叫
mService = null;
mKillButton.setEnabled(false);
mCallbackText.setText("Disconnected.");
Toast.makeText(Binding.this, R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
/** 與服務第二介面互動的連線類別 */
private ServiceConnection mSecondaryConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mSecondaryService = ISecondary.Stub.asInterface(service);
mKillButton.setEnabled(true);
}
public void onServiceDisconnected(ComponentName className) {
mSecondaryService = null;
mKillButton.setEnabled(false);
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
// 依介面名稱建立兩個連線,允許其他應用以相同介面替換遠端服務
bindService(new Intent(IRemoteService.class.getName()),
mConnection, Context.BIND_AUTO_CREATE);
bindService(new Intent(ISecondary.class.getName()),
mSecondaryConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
mCallbackText.setText("Binding.");
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
if (mService != null) {
try {
mService.unregisterCallback(mCallback);
} catch (RemoteException e) {
// 服務已崩潰無需特別處理
}
}
unbindService(mConnection);
unbindService(mSecondaryConnection);
mKillButton.setEnabled(false);
mIsBound = false;
mCallbackText.setText("Unbinding.");
}
}
};
private OnClickListener mKillListener = new OnClickListener() {
public void onClick(View v) {
// 要終止服務所在行程,需先取得其 PID
if (mSecondaryService != null) {
try {
int pid = mSecondaryService.getPid();
// 核心仍會限制可終止的 PID,通常只能終止自己的應用行程
Process.killProcess(pid);
mCallbackText.setText("Killed service process.");
} catch (RemoteException ex) {
Toast.makeText(Binding.this, R.string.remote_call_failed,
Toast.LENGTH_SHORT).show();
}
}
}
};
// ---- 處理回呼的程式碼 ----
/** 用來接收遠端服務回呼的實作 */
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
/**
* 服務會定期呼叫此方法告知新值。注意:IPC 呼叫透過各行程的執行緒池分派,
* 因此這裡的程式碼「不會」跑在主執行緒;要更新 UI 必須用 Handler 跳過去。
*/
public void valueChanged(int value) {
mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
}
};
private static final int BUMP_MSG = 1;
private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case BUMP_MSG:
mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
};
}
Android MediaPlayer 實戰:播放、暫停、快轉,一個都不能少
要在 App 裡放音樂或影片,Android 提供了 MediaPlayer 這個類別作為進入點。它被封裝在系統的媒體播放服務之上,讓你不必自己處理解碼細節,就能播放本機
開啟 ListView 側邊快速滾動滑塊:一行屬性搞定 fastScroll
不少開發者不知道 ListView 右側那個快速滾動滑塊(fast scroll thumb)該怎麼啟用,其實只要一行設定。 用 XML 布局的話,在 ListView
Android 網絡圖片查看顯示的實現方法
很多應用都需要從網路載入圖片並顯示。常見做法是在介面中放置輸入框、按鈕與 ImageView,當使用者輸入圖片網址並點擊按鈕後,再於背景執行緒中下載圖片資料。關鍵流程下載
Android 單元測試實例分析:從設定到執行
本文以實例說明 Android 單元測試的用法。在實際開發中,撰寫 Android 軟體的過程需要不斷測試,而 JUnit 測試框架正是正規開發必備的技術。透過 JUni