aidl用于android中进程间通信,远程服务端的接口方法在aidl中声明,当客户端 绑定服务器成功后返回的binder对象转成aidl支持的类型并调用之前声明的接口方法即可实现客户端与远程服务器的跨进程通信。
其实不提供aidl文件也可以实现Binder,之所以提供aidl文件,是为了方便系统为我们生成代码,我们也可以手动写一个Binder。aidl支持如下数据类型:
1、基本数据类型6、aidl本身
值得注意的是除了基本类型,其他类型参数需要加上流向:in(只能客户端流向服务端),out(只能服务端流向客户端),inout(可以在客户端和服务端双向流动)
客户端调用远程服务是同步的,如果客户端在UI线程调用远程服务就有可能因为服务端的耗时方法导致ANR,所以如果想要异步调用就新开个线程吧。
private void bindKeyguardService() {
new Thread(new Runnable() {
@Override
public void run() {
LogUtil.d("---bindFaceUnlokService start");
Intent localIntent = new Intent();
localIntent.setClassName(Const.KEYGUARD_PACKAGE, Const.KEYGUARD_CLASS);
if (bindService(localIntent, mServiceConn, Context.BIND_AUTO_CREATE)) {
LogUtil.d("---bindFaceUnlockService success---");
} else {
LogUtil.d("---bindFaceUnlokService failed---");
}
LogUtil.d("---bindFaceUnlokService end");
}
}).start();
}
private ServiceConnection mServiceConn = new ServiceConnection() {
public void onServiceConnected(ComponentName paramAnonymousComponentName, IBinder binder) {
LogUtil.v("*** FaceUnlock connected (yay!)");
mService = IService.Stub.asInterface(binder);
}
public void onServiceDisconnected(ComponentName paramAnonymousComponentName) {
LogUtil.d("*** FaceUnlock onServiceDisconnected");
mService = null;
}
};
log打印如下:
05-25 18:18:35.352 7944-7966: (FaceUnlockService.java:568)run->---bindFaceUnlokService start
05-25 18:18:35.359 7944-7966: (FaceUnlockService.java:572)run->---bindFaceUnlockService success---
(FaceUnlockService.java:576)run->---bindFaceUnlokService end
05-25 18:18:35.428 7944-7944: (FaceUnlockService.java:584)onServiceConnected->*** FaceUnlock connected (yay!)
mRemote.transact(Stub.TRANSACTION_exec, _data, _reply, 0);
transact(int code, Parcel data, Parcel reply, int flags)
如果接口用oneway修饰,那么参数变为1,接收远程服务方法是异步的
mRemote.transact(int code, Parcel data, Parcel reply, android.os.IBinder.FLAG_ONEWAY);
/**
* Flag to {@link #transact}: this is a one-way call, meaning that the
* caller returns immediately, without waiting for a result from the
* callee. Applies only if the caller and callee are in different
* processes.
*
* The system provides special ordering semantics for multiple oneway calls
* being made to the same IBinder object: these calls will be dispatched in the
* other process one at a time, with the same order as the original calls. These
* are still dispatched by the IPC thread pool, so may execute on different threads,
* but the next one will not be dispatched until the previous one completes. This
* ordering is not guaranteed for calls on different IBinder objects or when mixing
* oneway and non-oneway calls on the same IBinder object.
*/
int FLAG_ONEWAY = 0x00000001;