AIDL定義
AIDL(Andrid接口定義語言)通常用于進(jìn)程間通訊。編譯器根據(jù)AIDL文件生成一系列對(duì)應(yīng)的Java類,,通過預(yù)先定義的接口以及Binder機(jī)制達(dá)到進(jìn)程間通訊的目的。說白了,AIDL就是定義一個(gè)接口,客戶端(調(diào)用端)通過bindService來與遠(yuǎn)程服務(wù)端建立一個(gè)連接,在建立連接成功后會(huì)返回一個(gè)IBnder對(duì)象,該對(duì)象是服務(wù)端Binder的BinderProxy,在建立連接時(shí),客戶端會(huì)通過asInterface函數(shù)將BinderProxy對(duì)象包裝成本地的Proxy,并將遠(yuǎn)程服務(wù)端的BinderProx對(duì)象賦值給Proxy類的mRemote字段,就是通過mRemote執(zhí)行遠(yuǎn)程函數(shù)的調(diào)用。
AIDL實(shí)現(xiàn)
新建一個(gè)AIDL文件,在AS中File-New-AIDL-AIDL file,我們創(chuàng)建一個(gè)SsoAuth.aidl文件,里面會(huì)默認(rèn)有一個(gè)baseTypes函數(shù)。我們?cè)诔绦蚝竺嫣砑右粋€(gè)ssoAuth函數(shù)用于SSO授權(quán)。代碼如下:
interface SsoAuth {
/**
* 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);
void ssoAuth(String name,String pwd);
}
因?yàn)榭蛻舳耸钦{(diào)用端,因此,只需要定義AIDL文件,此時(shí)重新build一下工程就會(huì)生成一個(gè)SsoAuth.java類,該類根據(jù)SsoAuth.aidl自動(dòng)生成,包含了我們?cè)?code>AIDL文件成定義的函數(shù)。因?yàn)?code>AIDL通常用于進(jìn)程間通訊,因此,我們新建一個(gè)被調(diào)用的工程,我們命名為aidl_server,然后將客戶端的AIDL文件夾復(fù)制到aidl_server的app/src/main目錄下,如圖所示:

此時(shí)相當(dāng)于在客戶端和被調(diào)用端都有同一份SsoAuth.aidl文件,他們的包名、類型完全一致,生成的SsoAuth.java類也完全一致,這樣在遠(yuǎn)程調(diào)用時(shí)它們就能夠擁有一致的類型。Rebuild被調(diào)用工程之后就會(huì)生成SsoAuth.java文件,該文件中有一個(gè)Stub類實(shí)現(xiàn)了SsoAuth接口。我們首先需要定義一個(gè)Service子類,然后在定義一個(gè)繼承Stub的子類,并且在Service的onBind函數(shù)中返回這個(gè)Stub子類的對(duì)象。
public class SsoAuthService extends Service {
private String TAG = "TAG";
SsoAuthImpl mBinder = new SsoAuthImpl();
public SsoAuthService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class SsoAuthImpl extends SsoAuth.Stub {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
Log.i(TAG, "basicTypes: ");
}
@Override
public void ssoAuth(String name, String pwd) throws RemoteException {
Log.i(TAG, "ssoAuth: >>>"+name+" 密碼:>"+pwd);
}
}
}
從上述代碼中我們可以看到,實(shí)際上完成功能的繼承自Stub的SsoAuthImpl類,Service只是提供了一個(gè)讓SsoAuthImpl依附的外殼。完成SsoAuthService之后我們需要注冊(cè)到清單文件中,代碼如下:
<service
android:name=".SsoAuthService"
android:process=":remote"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.shengmingji.aidl_server.SsoAuthService" />
</intent-filter>
</service>
然后先運(yùn)行服務(wù)端應(yīng)用,并且在客戶端中完成調(diào)用Server的代碼??蛻舳?code>Activity的代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bindServer(View view) {
if (ssoAuth == null) {
Intent intent = new Intent("com.shengmingji.aidl_server.SsoAuthService");
bindService(intent, connection, BIND_AUTO_CREATE);
} else {
try {
ssoAuth.ssoAuth("hahaha","123456");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private SsoAuth ssoAuth;
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ssoAuth = SsoAuth.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
ssoAuth = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
上述代碼中,運(yùn)行程序點(diǎn)擊登錄按鈕是會(huì)想Server端發(fā)起Service請(qǐng)求,在建立連接之后會(huì)將Binder對(duì)象轉(zhuǎn)換為SsoAuth對(duì)象,然后調(diào)用SsoAuth對(duì)象的SsoAuth函數(shù)。此時(shí)ssoAuth函數(shù)實(shí)際上調(diào)用的就是Server端SsoAuthImpl類的實(shí)現(xiàn)。運(yùn)行程序點(diǎn)擊登錄按鈕,運(yùn)行結(jié)果
12-14 20:20:59.957 18625-18625/? D/AndroidKeyStoreProvider: not overseas product
12-14 20:20:59.987 18625-18625/com.shengmingji.aidl_server:remote I/TAG: onCreate:
12-14 20:21:10.337 18625-18644/com.shengmingji.aidl_server:remote I/TAG: ssoAuth: >>>hahaha 密碼:>123456
12-14 20:21:11.807 18625-18643/com.shengmingji.aidl_server:remote I/TAG: ssoAuth: >>>hahaha 密碼:>123456
這一切的核心都是通過AIDL 文件生成的Stub類以及其背后的Binder。首先我們看看生成的SsoAuth.java,Stub類就是該文件中的內(nèi)部類。代碼如下:
public interface SsoAuth extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements com.shengmingji.aidl.SsoAuth {
private static final java.lang.String DESCRIPTOR = "com.shengmingji.aidl.SsoAuth";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an
* com.shengmingji.aidl.SsoAuth interface,
* generating a proxy if needed.
*/
public static com.shengmingji.aidl.SsoAuth asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.shengmingji.aidl.SsoAuth))) {
return ((com.shengmingji.aidl.SsoAuth) iin);
}
return new com.shengmingji.aidl.SsoAuth.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_basicTypes: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
long _arg1;
_arg1 = data.readLong();
boolean _arg2;
_arg2 = (0 != data.readInt());
float _arg3;
_arg3 = data.readFloat();
double _arg4;
_arg4 = data.readDouble();
java.lang.String _arg5;
_arg5 = data.readString();
this.basicTypes(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5);
reply.writeNoException();
return true;
}
case TRANSACTION_ssoAuth: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
this.ssoAuth(_arg0, _arg1);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.shengmingji.aidl.SsoAuth {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(anInt);
_data.writeLong(aLong);
_data.writeInt(((aBoolean) ? (1) : (0)));
_data.writeFloat(aFloat);
_data.writeDouble(aDouble);
_data.writeString(aString);
mRemote.transact(Stub.TRANSACTION_basicTypes, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public void ssoAuth(java.lang.String name, java.lang.String pwd) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(name);
_data.writeString(pwd);
mRemote.transact(Stub.TRANSACTION_ssoAuth, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_ssoAuth = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException;
public void ssoAuth(java.lang.String name, java.lang.String pwd) throws android.os.RemoteException;
}
首先,他聲明了兩個(gè)方法basicTypes()和ssoAuth()。顯然這就是我們?cè)?code>SsoAuth.aidl中所聲明的方法,同時(shí)它還聲明了兩個(gè)整數(shù)的id分別用于標(biāo)識(shí)這兩個(gè)方法,這兩個(gè)id用于標(biāo)識(shí)在transact過程中客戶端所請(qǐng)求的到底哪個(gè)方法。接著聲明了一個(gè)內(nèi)部類Stub,這個(gè)Stub就是一個(gè)Binder類,當(dāng)客戶端和服務(wù)端都位于同一個(gè)進(jìn)程中時(shí),方法調(diào)用不會(huì)走跨進(jìn)程的transact過程,二兩者位于同一個(gè)進(jìn)程時(shí),方法調(diào)用需要走transac過程。這個(gè)邏輯是Stub的內(nèi)部代理類Proxy來完成。
Stub類說明
在SsoAuth.java中自動(dòng)生成了SsoAuth接口,該接口中有一個(gè)ssoAuth函數(shù),但最重要的是生成了一個(gè)Stub類,該類繼承自Binder類,并實(shí)現(xiàn)了SsoAuth接口。Stub里面最重要的就是asInterface函數(shù),在這個(gè)函數(shù)總會(huì)判斷obj參數(shù)的類型,如果該obj是本地的接口類型,則認(rèn)為不是進(jìn)程間調(diào)用,此時(shí)將obj轉(zhuǎn)換成SsoAuth類型;否則會(huì)通過自動(dòng)生成的另一個(gè)內(nèi)部類Proxy來包裝obj,將其賦值給Proxy中的mRemote字段。Proxy類也實(shí)現(xiàn)了SsoAuth接口,不同的是它是通過Binder機(jī)制來與遠(yuǎn)程進(jìn)程進(jìn)行交互,例如,在ssoAuth函數(shù)中,Proxy將通過Binder機(jī)制向服務(wù)器傳遞請(qǐng)求和數(shù)據(jù),它請(qǐng)求的類型為TRANSACTION_ssoAuth,參數(shù)分別是String類型的name和pwd。
對(duì)于服務(wù)器來說,它也有一份SsoAuth.aidl以及SsoAuth.java。但不同的是服務(wù)端是指令的接收端,客戶端的調(diào)用會(huì)通過Binder機(jī)制傳遞到服務(wù)器,最終調(diào)用Stub類中的onTransact函數(shù),可以看到在
case TRANSACTION_ssoAuth: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
java.lang.String _arg1;
_arg1 = data.readString();
this.ssoAuth(_arg0, _arg1);
reply.writeNoException();
return true;
}
中執(zhí)行了this.ssoAuth(arg0, arg1) 函數(shù),意思就是當(dāng)接到客戶端的TRANSACTION_ssoAuth請(qǐng)求時(shí),執(zhí)行this.ssoAuth(_arg0, _arg1)函數(shù),通過客戶端分析我們知道,當(dāng)我們調(diào)用ssoAuth函數(shù)時(shí)實(shí)際上就是通過mRemote向服務(wù)端提交了一個(gè)TRANSACTION_ssoAuth請(qǐng)求,因此,這兩端通過Binder機(jī)制就對(duì)接上了,可以理解為C/S模式。
而在客戶端調(diào)用bindService之后,如果綁定成功則會(huì)調(diào)用onServiceConnected,這里的Service對(duì)象就是BinderProxy類型,經(jīng)過asInterface轉(zhuǎn)換后被包裝成了Proxy類型,但是調(diào)用的時(shí)候,執(zhí)行的是服務(wù)端SsoAuthImpl中的ssoAuth函數(shù)。因此SsoAuthImpl實(shí)例mBinder被服務(wù)端包裝成了BinderProxy類型,在經(jīng)過客戶端的Proxy進(jìn)行包裝,通過Binder機(jī)制進(jìn)行數(shù)據(jù)傳輸,實(shí)現(xiàn)進(jìn)程間調(diào)用。
Demo
參考
《Android開發(fā)進(jìn)階》