1.bindService调用远端AIDL服务回调是在主线程执行
//AIDL接口
interface IStudentCallback {
oneway void onError(int code,String msg);
oneway void recevierData(in Student student);
}
interface IStudentService {
List<Student> getStudentList();
oneway void getStudentList(in IStudentCallback cb);
oneway void addStudent(in Student student);
}
//绑定AIDL服务
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mStudentService = IStudentService.Stub.asInterface(service);
//这里是在主线程执行
}
@Override
public void onServiceDisconnected(ComponentName name) {
//这里是在主线程执行
}
};
2.绑定AIDL成功获取到mStudentService 接口后,调用接口方法是同步还是异步
- 没有使用oneway关键字修饰
如:mStudentService.getStudentList()方法就是阻塞同步的,执行这个方法时等待服务端执行完成才返回,服务端方法是在Binder线程池中执行的;如果这个方法很耗时间,mStudentService.getStudentList()就不能在主线程执行,避免发生ANR
- 定义的方法使用 oneway关键之修饰
如:mStudentService.addStudent(in Student student)方法就是非阻塞异步的,执行这个方法时立即返回,服务端方法任然是在Binder线程池中执行的;什么情况适合使用oneway,只需要传递数据不在意返回结果或者是使用回调的方式
tips:oneway 修饰的方法不能有返回值,这个很好理解,立即返回还能有毛线的返回值
3.绑定AIDL成功获取到mStudentService 接口中有定义远程回调
IStudentService的getStudentList(in IStudentCallback cb)方法,实现了一个对等的binder回调
<1>回调方法直接在服务端方法中调用:
客户端阻塞,阻塞时间为两个之和,客户端(IStudentCallback 的方法)回调在调用方法对应线程(如在主线程也是一样,但是show toast 出不来),服务端线程任然在binder线程中执行
<2>回调方法在服务器端方法中开线程调用
客户端阻塞,阻塞时间为服务器端时间,客户端(IStudentCallback 的方法)回调在客服端binder线程中执行,服务端线程任然在binder线程中执行
4.IStudentCallback回调实现中调用服务器端方法
在3基础上,再在(IStudentCallback 的方法)回调中调用服务器端方法是在子线程中执行不是在binder线程
总结:调用binder中非oneway方法是阻塞的并且方法是在子线程中执行,调用oneway方法不阻塞,任然在子线程中执行
此文要是对你有帮助,如果方便麻烦点个赞,谢谢!!!