1.創(chuàng)建實體bean,繼承Parcelable序列化接口
package ip.cynic.aidl;
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person() {
}
//從序列后的對象中創(chuàng)建原始對象。
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
//返回當(dāng)前對象的內(nèi)容描述。1為含有文件描述,0則反之。幾乎所有情況都為0。
@Override
public int describeContents() {
return 0;
}
//將當(dāng)前對象寫入序列化結(jié)構(gòu)中,其中 flags 標(biāo)識為0或1.為1時標(biāo)識當(dāng)前對象需要作為返回值返回,不能立即釋放資源,
//幾乎所有情況都為0。
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeInt(age);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
// 從序列化接口創(chuàng)建實體bean
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
//創(chuàng)建指定長度的原始對象組
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.編寫AIDL文件
-
AIDL支持的類型
- 基本數(shù)據(jù)類型
- String 和 CharSequence
- 實現(xiàn)了 Parcelable 接口的對象
- AIDL 接口本身的類型
- 對于集合,AIDL 僅支持兩種類型
- ArrayList,且里面的每個元素必須被 AIDL 支持
- HashMap,且里面的每個 key和 value 必須被 AIDL 支持
-
AIDL使用的Parcelable的對象也要建一個與之同名的AIDL文件聲明
package ip.cynic.aidl;
parcelable Person;
-
創(chuàng)建業(yè)務(wù)接口,除基本類型外需要對參數(shù)標(biāo)識in/out/inout
package ip.cynic.aidl; import ip.cynic.aidl.Person; interface RemoteAidl { List<Person> getPerson(in Person person); }
3.創(chuàng)建服務(wù)的service
public class AidlService extends Service {
public AidlService() {
}
private List<Person> mPersonLists;
@Override
public IBinder onBind(Intent intent) {
mPersonLists = new ArrayList<>();
return mIBinder;
}
private IBinder mIBinder = new RemoteAidl.Stub() {
@Override
public List<Person> getPerson(Person person) throws RemoteException {
mPersonLists.add(person);
return mPersonLists;
}
};
}
4.客戶端將服務(wù)端的AIDL與bean拷貝過來包名要一致,在Activity中綁定service
public class MainActivity extends AppCompatActivity {
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mRemoteAidl = RemoteAidl.Stub.asInterface(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
private RemoteAidl mRemoteAidl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setComponent(new ComponentName("ip.cynic.aidl","ip.cynic.aidl.AidlService"));
bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
}
public void bind(View view) throws RemoteException {
List<Person> list = mRemoteAidl.getPerson(new Person("aa", 9));
Log.e("list",list.toString());
}
}
點擊bind按鈕后,控制臺會輸出,每點擊一次對象增加一個。
5.AIDL生成Java文件主要方法說明
getPerson()為aidl文件中聲明的方法。
int類型 TRANSACTION_getPerson 為標(biāo)識在transact過程中客戶端調(diào)用的那個方法。
DESCRIPTOR Binder的唯一標(biāo)識,一般為當(dāng)前Binder的類名。
-
Stub內(nèi)部類,其實就是一個Binder類。
-
asInterface(android.os.IBinder obj) 首先拿一個字符串(接口類全名)到本地進程查詢(queryLocalInterface),查詢不到則 說明這是一個跨進程調(diào)用;返 回Stub的內(nèi)部 Proxy類。
public static ip.cynic.aidl.RemoteAidl asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof ip.cynic.aidl.RemoteAidl))) {
return ((ip.cynic.aidl.RemoteAidl) iin);
}
return new ip.cynic.aidl.RemoteAidl.Stub.Proxy(obj);
} asBinder() 返回當(dāng)前的Binder對象。
-
onTransact 運行在服務(wù)端的Binder線程池中,當(dāng)客戶端發(fā)起跨進程通訊時,遠程請求會通過系統(tǒng)底層封裝交由此方法處理。
public Boolean onTransact(int code,Parcelable data,Parcelable reply,int flags)
服務(wù)端通過code確認客戶端請求的目標(biāo)方法是什么,接著從data中取出目標(biāo)方法所需的參數(shù)(如果有),然后執(zhí)行目標(biāo)方法。當(dāng)目標(biāo)方法執(zhí)行完后,向reply中寫入返回值(如果有)。如果方法返回值為false,那么服務(wù)端的請求會失敗,利用這個特性我們可以來做權(quán)限驗證。
Proxy#getPerson 該方法由客戶端調(diào)用,首先創(chuàng)建該方法所需要的輸入型Parcel對象_data、輸出型對象_reply和返回值對象List;
然后把該方法的參數(shù)寫入到_data中(如果有參數(shù)的話);接著調(diào)用transact方法來發(fā)起RPC遠程調(diào)用請求,同時線程掛起;然后服務(wù)端的OnTranscat方法會被調(diào)用,直到RPC返回,當(dāng)前線程繼續(xù)執(zhí)行,并從_reply中取出數(shù)據(jù)。
-
6.Binder中兩個很重要的方法linkToDeath和unlinkToDeath
由于 Binder 是可能意外死亡的,往往是服務(wù)端進程異常停止,會導(dǎo)致客戶端的遠程調(diào)用失敗,有兩種方法解決這個問題。一是在 onServiceDisconnected 中重連遠程服務(wù);二是給 Binder 設(shè)置一個死亡代理(DeathRecipient),當(dāng) Binder 死亡的時候客戶端就會收到通知,客戶端可以選擇重新發(fā)起連接請求進而恢復(fù)連接了。
private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
Log.d(TAG, "binder died. tname:" + Thread.currentThread().getName());
if (mRemoteAidl == null)
return;
mRemoteAidl.asBinder().unlinkToDeath(mDeathRecipient, 0);
mRemoteAidl = null;
// TODO:這里重新綁定遠程Service
}
};
然后在 ServiceConnection#onServiceConnected 中注冊:
mRemoteAidl.asBinder().linkToDeath(mDeathRecipient, 0);
文中大多知識點來自《Android開發(fā)藝術(shù)探索》