【android官方文件】android AIDL
阿新 • • 發佈:2019-02-11
概述
AIDL(安卓介面解釋語言)和其他的IDLs類似。可以定義程式介面讓客戶端和service進行跨程序的通訊(IPC)。在android中,一個程序通常不能訪問另一個程序的記憶體。所以,他們的物件需要被分解成更原始的單位,直到系統可以理解,並且集結這些物件穿過程序間的邊界。編寫這些集結的程式碼是乏味的,所以Android通過AIDL幫你處理這些工作。注意:只有在以下情況使用AIDL是有必要的,允許不同程式的客戶端訪問你的service,並且在service中處理多執行緒。如果你不需要執行當前不同程式間的IPC,就需要通過實現Binder建立一個介面,如果想執行IPC,但不需要處理多執行緒,使用Messenger類實現你的介面。不管怎樣,在實現AIDL前,一定要理解了Bound Services。
開始設計你的AIDL介面前,需要知道呼叫AIDL是直接的函式呼叫。你不能假定是哪個執行緒呼叫了這個介面。這裡的區別取決於是一個本地程序的執行緒還是遠端程序的執行緒。
定義一個AIDL介面
必須使用java的語法在.aidl字尾的檔案裡定義AIDL介面,然後儲存在src/目錄下。你建立的每一個包含.aidl檔案的程式,sdk會基於.aild檔案生成IBinder介面,並儲存在專案的gen/目錄下。service必須適時地實現IBinder介面。元件可以繫結到service,並且呼叫IBinder的方法去執行IPC。
使用AIDL建立一個繫結的service,需要以下步驟。
1.建立.aidl檔案
這個檔案通過方法簽名定義了設計介面。
2.實現介面
基於.aidl檔案 ,sdk生成一個java語言的介面。這個介面有個內部抽象類,這個類繼承自Binder,叫Stub。必須繼承Stub類並實現方法。
3.公開介面給客戶端
實現一個Service,並重寫onBind()返回一個Stub類的實現。
警告:第一次釋出之後,對AIDL的任何改變都必須保持向後相容,這是為了避免破壞其他程式對你的service的使用。就是說,因為你的.aidl檔案必須拷貝到其他程式,為了能訪問你的介面,你必須保持對原始介面的支援。
1.建立.aidl檔案
AIDL使用一個簡單的語法,宣告一個介面,在接口裡有一個或多個方法,這個方法可以帶引數,返回資料。引數和返回值可以是任意型別,甚至是其他AIDL介面。必須使用java語言建立.aidl檔案。每一個.aidl檔案必須定義一個介面並只要介面宣告和方法。
預設的,AIDL支援一下資料型別:
所有的原始資料型別(比如,int,long,char,boolean,等等)
String
CharSequence
List
所有List中的元素必須是支援的資料型別或者AIDL生成的介面或者parcelables。一個List應該可以任意被使用為“generic”類(比如,List<String>)。事實上具體類是ArrayList在接受資料,雖然方式是使用List介面。
Map
所有Map中的元素必須是支援的資料型別或者AIDL生成的介面或者parcelables。一般的maps,(比如這些形式Map<String,Integer>是不被支援的)。事實上具體類是HashMap在接受資料,雖然方式是使用Map介面。
你必須為每個沒有上面列出來的型別import依賴包,即使他們被定義在同一個包種。
當定義了service介面,要意識到:
方法可以帶0個或多個引數,返回一個數據或者void。
所有非原始資料型別引數需要一個指向標記指示資料的走向。要麼in,out,或者inout(見下面的例子)原始資料預設是in,而且就這一種。
注意:你需要更具真實需要限制方向,因為集結這些引數是昂貴的。
所有.anil檔案中的註釋都包含在IBinder介面中(除了inport和package前的註釋)
在AIDL中,只支援方法,不可以放靜態域
以下是一個.aidl檔案的例子:
// IRemoteService.aidl
package com.example.android;
// Declare any non-default types here with import statements
/** Example service interface */
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
儲存.aidl檔案到專案中的src/目錄下,sdk在gen/目錄下生成IBinder介面。生成的檔名和.aidl的檔名一樣,但是一個是.java字尾(比如 IRemoteService.aidl 結果會是 IRemoteService.java)如果使用eclipse,binder的生成會立即執行。如果不使用eclipse,Ant會在下次構建app的時候生成。
2.實現介面
建立app的時候,sdk生成.java介面檔案。這個介面包括一個叫Stub的子類,Stub是父介面的抽象實現(比如,YourInterface.Stub)並且在.aidl檔案中宣告所有的方法。注意:Stub也會定義一些helper方法,最顯著的是asInterface(),它擁有一個IBinder(通常會傳遞給一個客戶端的onServiceConnected()回撥方法中)並返回一個stub介面的例項。
為了實現從.aidl中生成的介面,繼承Binder介面(比如,YourInterfac.Stub)並且實現從.aidl檔案繼承過來的方法。
這裡有有個例子實現了一個叫IRemoteService的介面(在IRemoteService.aidl中定義了)使用了一個匿名例項:
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
現在mBinder是一個Stub類的例項(一個Binder),它給service定義了RPC介面。下一步,這個例項暴露給客戶端,所以他們可以和service互動。當實現AIDL介面的時候,有一些規則需要考慮:
- 在主執行緒中將要來的呼叫不會保證被執行,一開始你需要考慮多執行緒,並且建立的service是執行緒安全的。
- 預設的,RPC呼叫是同步的。如果知道service要花費幾毫秒時間去完成請求,你不應該從Activity的主執行緒中呼叫它,應為這可能阻塞程式(android可能顯示“Application is Not Responding”對話方塊)—你應該從非主執行緒中呼叫它。
- 你不要丟擲異常給呼叫者。
3.公開介面給客戶端
一旦你實現了service的介面,你需要把它暴露給客戶端,這樣他們能和它繫結。為了給service暴露介面,繼承Service並實現onBind()以返回Stub的例項(之前已經討論)。以下是一個暴露IRemoteServide的例子。public class RemoteService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// Return the interface
return mBinder;
}
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
}
現在,當一個客戶端(比如一個Activity)呼叫了bindService()連線到這個service,這個客戶端的onServiceConnected()回撥方法接受到了通過onBinde()返回的mBinder例項。
這個客戶端必須有可訪問的介面類,所以如果客戶端和service在不同的程式,客戶端的程式必須拷貝一份.aidl檔案到src/目錄下(生成android.os.Binder介面—提供客戶端訪問AIDL方法)。
當客戶端在onServiceConnected()回撥方法中接收到IBinder,必須呼叫YourServiceInterface.Stub.asInterface(service)轉換返回的引數為YourServiceInterface型別。比如:
IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
// Following the example above for an AIDL interface,
// this gets an instance of the IRemoteInterface, which we can use to call on the service
mIRemoteService = IRemoteService.Stub.asInterface(service);
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "Service has unexpectedly disconnected");
mIRemoteService = null;
}
};
更多例子,看ApiDemos中的 RemoteService.java類。
通過IPC傳遞物件
如果你想通過IPC介面從一個程序中傳遞一個類到另一個,你可以這麼做。然而,你必須確保你的類的程式碼在IPC通道的另一邊是可用的並且你的類必須支援了Parcelable介面。這很重要,因為它可以允許Android系統把物件分解成很多原始的單位,這些單位可以通過程序支配。為了建立一個支援Parcelable協議的類,你必須做如下工作:
1.確保你的類實現了Parcelable介面。
2.實現writeToParcel,它可以獲得物件的當前狀態,並寫到一個Parcel中。
3.給你的類增加一個叫CREATOR的靜態域,這個靜態域是一個物件實現了Parcelable.Creator介面。
4.最終,建立一個.aidl檔案,裡面申明parcelable類(在下面Rect.aidl檔案中顯示的那樣)。如果你在使用一個自定義構建的程序,不要新增.aidl檔案到你的構建中。對於c語言的標頭檔案一樣,這個.aidl檔案是不會被編譯的。
比如,這裡是一個Rect.aidl檔案去建立一個Rect類:
package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;
並且這裡是一個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中讀取了四個數字,但是要確保他們在呼叫者可接受的範圍內。呼叫一個IPC方法
這裡是一些步驟,一個類必須呼叫一個AIDL定義的遠端介面:1.在專案的src/目錄下包含.aidl檔案。
2.宣告一個IBinder介面的例項(在AIDL中生成)。
3.實現ServiceConnection。
4.呼叫Context.bindService(),傳遞實現了的ServiceConnection。
5.在onServiceConnected()實現中,你將接收到一個IBinder例項。呼叫YourInterfaceName.Stub.asInterface((IBinder)service)將引數轉換成YourInterface資料型別。
6.呼叫介面中定義的方法。當連線失敗的時候,你會接收到DeadObjectException 的異常。這是遠端方法的唯一異常。
7.為了斷開連線,要呼叫介面的 Context.unbindService()方法。
這裡是一些例子程式碼證明呼叫一個AIDL建立的service,從遠端serice獲得。
public static class Binding extends Activity {
/** The primary interface we will be calling on the service. */
IRemoteService mService = null;
/** Another interface we use on the service. */
ISecondary mSecondaryService = null;
Button mKillButton;
TextView mCallbackText;
private boolean mIsBound;
/**
* Standard initialization of this activity. Set up the UI, then wait
* for the user to poke it before doing anything.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_service_binding);
// Watch for button clicks.
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.");
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = IRemoteService.Stub.asInterface(service);
mKillButton.setEnabled(true);
mCallbackText.setText("Attached.");
// We want to monitor the service for as long as we are
// connected to it.
try {
mService.registerCallback(mCallback);
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
// As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mKillButton.setEnabled(false);
mCallbackText.setText("Disconnected.");
// As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
/**
* Class for interacting with the secondary interface of the service.
*/
private ServiceConnection mSecondaryConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// Connecting to a secondary interface is the same as any
// other interface.
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) {
// Establish a couple connections with the service, binding
// by interface names. This allows other applications to be
// installed that replace the remote service by implementing
// the same interface.
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 we have received the service, and hence registered with
// it, then now is the time to unregister.
if (mService != null) {
try {
mService.unregisterCallback(mCallback);
} catch (RemoteException e) {
// There is nothing special we need to do if the service
// has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
unbindService(mSecondaryConnection);
mKillButton.setEnabled(false);
mIsBound = false;
mCallbackText.setText("Unbinding.");
}
}
};
private OnClickListener mKillListener = new OnClickListener() {
public void onClick(View v) {
// To kill the process hosting our service, we need to know its
// PID. Conveniently our service has a call that will return
// to us that information.
if (mSecondaryService != null) {
try {
int pid = mSecondaryService.getPid();
// Note that, though this API allows us to request to
// kill any process based on its PID, the kernel will
// still impose standard restrictions on which PIDs you
// are actually able to kill. Typically this means only
// the process running your application and any additional
// processes created by that app as shown here; packages
// sharing a common UID will also be able to kill each
// other's processes.
Process.killProcess(pid);
mCallbackText.setText("Killed service process.");
} catch (RemoteException ex) {
// Recover gracefully from the process hosting the
// server dying.
// Just for purposes of the sample, put up a notification.
Toast.makeText(Binding.this,
R.string.remote_call_failed,
Toast.LENGTH_SHORT).show();
}
}
}
};
// ----------------------------------------------------------------------
// Code showing how to deal with callbacks.
// ----------------------------------------------------------------------
/**
* This implementation is used to receive callbacks from the remote
* service.
*/
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
/**
* This is called by the remote service regularly to tell us about
* new values. Note that IPC calls are dispatched through a thread
* pool running in each process, so the code executing here will
* NOT be running in our main thread like most other things -- so,
* to update the UI, we need to use a Handler to hop over there.
*/
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);
}
}
};
}