注:本文是我早些時候在eoe上發布的一篇文章
由於每個應用程序都運行在自己的進程空間,並且可以從應用程序UI運行另一個服務進程,而且經常會在不同的進程間傳遞對象。在Android平台,一個進程通常不能訪問另一個進程的內存空間,所以要想對話,需要將對象分解成操作系統可以理解的基本單元,並且有序的通過進程邊界。
以下講對如何實現AIDL調用進行講解,本文包括AIDL接口調用,回調,以及傳遞復雜數據類型
Demo運行效果圖
Aidl文件
Person.aidl
package com.archermind.aidl;
parcelable Person;
ITaskBinder.aidl
package com.archermind.aidl;
import com.archermind.aidl.ITaskCallBack;
import com.archermind.aidl.Person;
interface ITaskBinder {
void fuc01();
void fuc02();
String fuc03(in Person person);
void registerCallBack(ITaskCallBack cb);
void unregisterCallBack();
}
ITaskCallBack.aidl
package com.archermind.aidl;
interface ITaskCallBack {
void onActionBack(String str);
}
先看Myservice的代碼
服務端實現了AIDL的相關接口,供客戶端調用
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
private final ITaskBinder.Stub mBinder=new ITaskBinder.Stub() {
@Override
public void unregisterCallBack() throws RemoteException {
// TODO Auto-generated method stub
Log.v(TAG,"unregisterCallBack...");
mTaskCallBack=null;
}
@Override
public void registerCallBack(ITaskCallBack cb) throws RemoteException {
// TODO Auto-generated method stub
Log.v(TAG,"registerCallBack...");
mTaskCallBack=cb;
}
@Override
public void fuc01() throws RemoteException {
// TODO Auto-generated method stub
Log.v(TAG,"fuc01...");
}
@Override
public void fuc02() throws RemoteException {
// TODO Auto-generated method stub
Log.v(TAG,"fuc02...");
mTaskCallBack.onActionBack("hello world");
}
@Override
public String fuc03(Person person) throws RemoteException {
// TODO Auto-generated method stub
String name=person.getName();
String descrip=person.getDescrip();
int sex=person.getSex();
String ret="";
if(sex==0){
ret="Hello "+name+",you are handsome"+"("+descrip+")";
}else{
ret="Hello "+name+",you are beautiful"+"("+descrip+")";
}
return ret;
}
};
客戶端實現回調接口
private final ITaskCallBack.Stub mCallBack=new ITaskCallBack.Stub() {
@Override
public void onActionBack(String str) throws RemoteException {
// TODO Auto-generated method stub
Log.v(TAG,"onActionBack str="+str);
}
};
客戶端如何與服務器綁定並建立連接
Intent intent=new Intent("com.archermind.aidl.myservice");
bindService(intent,mConnection,BIND_AUTO_CREATE);
private ServiceConnection mConnection=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService=ITaskBinder.Stub.asInterface(service);
try {
mService.registerCallBack(mCallBack);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v(TAG,"onServiceConnected");
}