-
JAVA的默认基本数据类型(String,int。。。 short除外)
-
List和Map
-
其它的AIDL接口
-
实现Parcelable的实体类
- 创建aidl
①创建实体类并实现Parcelable接口
②新建aidl文件,在其下面创建aidl的映射文件和接口文件
③通过build后生成binder的java文件
- 服务端
①创建service,在其中创建上面生成binder的实例,实现接口定义的方法
②在onBind()中返回
- 客户端
①实现ServiceConnection接口,在其中拿到AIDL类
②用bindService()绑定service
③使用aidl中的操作
AIDL实例:
(先演示一个小的)
服务端做出了一个A+B的功能,而客户端没有这个功能的时候他要去服务端调用这个功能。
首先在创建IMyaidl文件
// IMyaidl.aidl
package com.rikka.myaidl2;
// Declare any non-default types here with import statements
interface IMyaidl {
/**
-
Demonstrates some basic types that you can use as parameters
-
and return values in AIDL.
*/
int add(in int num1,in int num2);
}
因为只是个a+b的功能,所以没有实体类呀parcelable的说法
然后点个锤子make project产生myaidl
此时去服务端完成这个a+b的功能,新建myservice类
在其中实现onbind()和Stub()
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mIbinder;
}
private IBinder mIbinder = new IMyaidl.Stub() {
@Override
public int add(int num1, int num2) throws RemoteException {
return num1+num2;
}
};
}
这里的 new IMyaidl.Stub()函数的返回类型是Ibinder,它先实现IMyaidl里面的接口功能,然后向上转型为Ibinder类型,同时通过onBind()传出。这样做是为了当客户端的activity要去用这个服务端的这个功能时,客户端先要绑定这个service,这时候客户端就能得到这个IBinder了。
接下来客户端要绑定服务,并且通过传入两个值a和b给服务端,让服务端完成a+b
首先要客户端实现接口 ServiceConnection ,在连接服务的时候得到AIDL类
IMyaidl im;
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
im = IMyaidl.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
im = null;
}
};
这里的 asInterface(service) 就是将绑定之后(现在还没有绑定服务,等下通过bindservice()绑定服务得到了ibinder)将Ibinder转化为aidl类。im就是这个aidl类。如下:
Intent intent = new Intent(getApplicationContext(),MyService.class);
bindService(intent,mConnection,BIND_AUTO_CREATE);
最后通过button来实现a+b