什么是AIDL
AIDL是一个缩写,全称是Android Interface Definition Language(Android接口定义语言)。主要用于进程间通信
创建AIDL
创建AIDL文件跟创建interface类文件类似,只是文件后缀为.aidl,然后clean project,build project会自动生成带stub 实现binder的类文件。Android Studio可以通过右键要建aidl的包 -> New -> AIDL -> AIDL file 创建;生成的aidl文件会在 src/main/aidl/...pakcagename/*.aidl
编写AIDL接口
编写与interface类似;与interface不同的是aidl文件仅是声明函数(不支持变量,常量或extends,函数也不支持重载)。
interface IMyAidlInterface {
/**
* 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 aFunction(int iType);
}
函数参数和返回支持类型有:
1)基本类型(int,long,boolean,float,double,char,CharSequence,String),不支持基础类型的封装类型(Integer...)
2)复杂类型(Map,List,Parcelable,aild)。其中Map不支持泛型,List支持。Map,List的类型需要是1的类型(Integer等可支持)或者是Parcelable,aidl
注意:
使用Parcelable,aidl类型的时,无论是否在引用类所在包,都需要显示声明
复杂类型做为参数时需要提明tag:in、out或inout。in代表参数是外流入函数,函数内对参数的操作不会影响处部,out则是函数内修改会被同步至外部。inout则是双向(待进一步建立示例说明)
实现AIDL接口
实现AIDL不是实现(implement)接口,而是继承接口.stub类(在编写完接口后build会产生)
class MyInterface extends IMyAidlInterface .Stub {
void aFunction(int iType) {
//...
}
}
说明:AIDL方法的实现是系统为aidl开的线程中执行,而非Service所属应用的主线程(如果调用与Service是同一个应用进程,则会在主线程执行?待验证)。
一般aidl在Service的public IBinder onBind(Intent intent) 中返回:
public IBinder onBind(Intent intent) {
//可以根据不同intent中的特点(如action)创建不同的MyInterface
return new MyInterface();
}
调用AIDL接口
连接
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(getLocalClassName(), "service connected");
MyItnerface myItnerface = MyItnerface.Stub.asInterface(service);
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(getLocalClassName(), "service disconnected");
mBound = false;
}
};
Intent mIntentService = new Intent();
mIntentService.setAction(...);
mIntentService.setPackageName(...); //提供Servcie的应用包名
context.bindService(mIntentService, mServiceConnection,
int flags)
flags:Context.BIND_AUTO_CREATE
注意:
只有activities,services,和contentproviders可以绑定到一个service—你不能从一个broadcastreceiver绑定到service.
调用接口
myItnerface.aFunction(2);
注意:
接口调用是同步的,即aFunction的执行会hold住调用者的线程,因此一般线程中调用。
Android进程间通信之AIDL(三)—— deadObject异常处理
AIDL文件中使用实现接口Parcelable的类
Android ServiceConnection
——————————————————————————————————————————
如果该文章对您有用,请点个赞;如果对该文章有任何意见及不解之处请留言;谢谢翻阅!!!
——————————————————————————————————————————
网友评论