HelloAIDL-第一个用AIDL实现的binder调用
实现步骤
创建AIDL文件
使用AndroidStudio工具,右键app,按照下图示例创建一个AIDL文件
我们先在AIDL文件中写一个最简单的函数,例如:
interface IMyAidlInterface {
void bindSuccess();
}
编译生成binder接口函数
在菜单栏选择 Build - Make Project,不出意外的话会生成IMyAidlInterface.java文件,生成路径如下图所示
如果编译过程中出现错误,可以将Project Structure中的Compile SDK Version和Build Tool Version换成28
创建service服务端
新建内部类bindService继承IMyAidlInterface.stub,实现接口中定义的函数,并在service服务端的onBind函数中返回bindService的对象
private Binder mBinder;
public MyService() {
mBinder = new binderService();
}
private class binderService extends IMyAidlInterface.Stub {
@Override
public void bindSuccess() throws RemoteException {
Log.e("bindAidl", "bindSuccess");
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
创建客户端调用
-
新建serviceConnection类继承ServiceConnection的接口
重写onServiceConnected以及onServiceDisconnected的方法,并在onServiceConnected方法中将获取的service对象通过IMyAidlInterface.Stub.asInterface方法转换成IMyAidlInterface类型的对象
private IMyAidlInterface mBinder;
private class serviceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinder = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
- 创建intent对象并调用bindservice方法,将客户端和service端连接起来
Intent intent = new Intent(this, MyService.class);
bindService(intent, new serviceConnection(), Context.BIND_AUTO_CREATE);
- 在客户端就能通过mBinder对象调用service方法
mBinder.bindSuccess();