3个问题:什么是Binder?拿来干什么?怎么用?
什么是Binder?拿来干什么?
Binder 是Android 中的一个类,实现了IBinder 接口。
从IPC 角度:Binder 是 Android 中的一种跨进程通信方式,也可以理解为一种虚拟的物理设备,它的设备驱动是 /dev/binder,该方式在 Linux 中没有,
从 Android Framework 角度:Binder 是 ServiceManger 连接各种 Manager(ActivityManager、WindowManger等)和相应 MangerService 的桥梁
从 Android 应用层: Binder 是客户端和服务端进行通信的媒介,当 bindService 时,服务端会返回一个包含了服务端业务调用的 Binder 对象,通过这个Binder 对象,客户端就可以获取服务端提供的服务或数据,这里的服务包括普通服务和基于 AIDL 的服务
怎么用?
AIDL 文件创建:
1、创建 实现 Parcelable 接口的操作实体类 Book,以便序列化和反序列化
package com.example.yhadmin.aidldemo.bean;
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
public int bookId;
public String bookName;
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
private Book(Parcel in) {
bookId = in.readInt();
bookName = in.readString();
}
public static final Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(bookId);
dest.writeString(bookName);
}
}
2、创建 aidl 文件夹(和java文件夹平行同级),在其中创建接口 aidl 文件和实体类的映射 aidl 文件
在 main 文件夹下新建 aidl 文件夹,使用的包名要和 java 文件夹的包名一致:
2.1先创建实体类的映射 aidl 文件,Book.aidl:
// Book.aidl
package com.example.yhadmin.aidldemo.bean;
// 声明映射的实体类名称与类型,还要和声明的实体类在一个包里,自定义的对象需要声明为 parcelable 类型
parcelable Book;
在其中声明映射的实体类名称与类型,注意:这个 Book.aidl 的包名要和实体类包名一致
2.2、然后创建接口 aidl 文件,IBookManager.aidl:
// IBookManager.aidl
package com.example.yhadmin.aidldemo;
// Declare any non-default types here with import statements
import com.example.yhadmin.aidldemo.bean.Book;
/**
*IBookManager 是自定义的一个接口,里面有我们自定义的方法, 这里自定义了getBookList、addBook两个方法
*
*/
interface IBookManager {
//除了基本数据类型,其他类型的参数都需要标上方向类型:in(输入), out(输出), inout(输入输出)
List<Book> getBookList();//用于从远程服务端获取图书列表
void addBook(in Book book);//用于往图书列表中添加一本书
}
注意:尽管这里Book 类已经和 IBookManager 位于相同的包中,但是在 IBookManager 中仍然要导入Book 类,不然会抛异常
编译通过后,会在 gen 目录下的包名下会有一个IBookManager.java 类,如下:
分析系统为IBookManager.aidl 生成的 Binder 类,在gen 目录下
代码:
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: F:\\MyPro\\Example\\AIDLDEMO\\app\\src\\main\\aidl\\com\\example\\yhadmin\\aidldemo\\IBookManager.aidl
*/
package com.example.yhadmin.aidldemo;
public interface IBookManager
extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
//内部类 Stub,实际就是一个Binder 类
public static abstract class Stub
extends android.os.Binder
implements com.example.yhadmin.aidldemo.IBookManager
{
//Binder 的位移标识,一般用当前Binder 的类名表示
private static final java.lang.String DESCRIPTOR = "com.example.yhadmin.aidldemo.IBookManager";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.example.yhadmin.aidldemo.IBookManager interface,
* generating a proxy if needed.
*/
/**
* 用于将服务端的 Binder 对象转换成客户端所需的 AIDL 接口类型对象,这种转换过程是区分进程的,如果客户端
* 和服务端位于同一进程,那么此方法返回的就是服务端的 Stub 本身,否则返回的是系统封装后的 Stub.proxy 对象
* @param obj
* @return
*/
public static com.example.yhadmin.aidldemo.IBookManager asInterface(android.os.IBinder obj)
{
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
//判断服务端和客户端是否为同一进程
if (((iin != null) && (iin instanceof com.example.yhadmin.aidldemo.IBookManager))) {
return ((com.example.yhadmin.aidldemo.IBookManager) iin);
}
return new com.example.yhadmin.aidldemo.IBookManager.Stub.Proxy(obj);
}
/**
* 用于返回当前 Binder 对象
* @return
*/
@Override
public android.os.IBinder asBinder()
{
return this;
}
/**
* 该方法运行于服务端中的 Binder 线程池中,当客户端发起跨进程请求时,远程请求会通过系统底层封装后交由此方法
* 处理,该方法的原型为 public Boolean onTransact(int code, android.os.Parcel data,
* android.os.Parcel reply,int flags).服务端通过 code 可以确定客户端所请求的目标方法是什么,接着从 data 中
* 取出目标方法所需的参数(如果目标方法有参数),然后执行目标方法。当目标方法执行完毕后,就像 reply 中写入返回值
* (如果目标方法由返回值), 这就是onTransact 方法的执行过程。
* 需要注意的是,如果此方法返回 false,则客户端的请求会失败,因此我们可以利用这个特性来做权限验证,毕竟我们不希望
* 随便一个进程都能远程调用我们的服务
* @param code
* @param data
* @param reply
* @param flags
* @return
* @throws android.os.RemoteException
*/
@Override
public boolean onTransact(int code,
android.os.Parcel data,
android.os.Parcel reply,
int flags)
throws android.os.RemoteException
{
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getBookList: {
data.enforceInterface(DESCRIPTOR);
java.util.List<com.example.yhadmin.aidldemo.bean.Book> _result = this.getBookList();
reply.writeNoException();
reply.writeTypedList(_result);
return true;
}
case TRANSACTION_addBook: {
data.enforceInterface(DESCRIPTOR);
com.example.yhadmin.aidldemo.bean.Book _arg0;
if ((0 != data.readInt())) {//读取参数,获取addBook 方法所需的参数
_arg0 = com.example.yhadmin.aidldemo.bean.Book.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
this.addBook(_arg0);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
//Stub 内部类中的代理内部类
private static class Proxy
implements com.example.yhadmin.aidldemo.IBookManager
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override
public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
/**
* 该方法运行在客户端,当客户端远程调用此方法时,它的内部实现是这样的:首先创建该方法所需要的输入型 Parcel
* 对象_data、输出型 Parcel 对象_reply 和返回值对象List;然后把该方法的参数信息写入 _data中(如果有参数),
* 接着调用 transact 方法来发起 RPC(远程过程调用)请求,同时当前线程挂起,然后服务端的 onTransact 方法会被
* 调用,直到 RPC 过程返回后,当前线程继续执行,并从 _reply 中取出 RPC 过程的返回结果,最后返回 _reply中的数据
*
* @return
* @throws android.os.RemoteException
*/
@Override
public java.util.List<com.example.yhadmin.aidldemo.bean.Book> getBookList()//这里没有参数
throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List<com.example.yhadmin.aidldemo.bean.Book> _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
//调用IBinder 的transact 方法
mRemote.transact(Stub.TRANSACTION_getBookList, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArrayList(com.example.yhadmin.aidldemo.bean.Book.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
/**
* 该方法运行在客户端,它的执行过程和getBookList 是一样的,addBook 没有返回值,故它不需要从 _reply 中取出
* 返回值
* @param book
* @throws android.os.RemoteException
*/
@Override
public void addBook(com.example.yhadmin.aidldemo.bean.Book book)
throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((book != null)) {
_data.writeInt(1);
book.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_addBook, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
}
//标识两个方法,用于在跨进程中分辨客户端请求的是哪个方法
static final int TRANSACTION_getBookList = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_addBook = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
//声明了我们在IBookManager 接口中声明的getBookList、addBook 2个方法
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
//除了基本数据类型,其他类型的参数都需要标上方向类型:in(输入), out(输出), inout(输入输出)
public java.util.List<com.example.yhadmin.aidldemo.bean.Book> getBookList()
throws android.os.RemoteException;
public void addBook(com.example.yhadmin.aidldemo.bean.Book book)
throws android.os.RemoteException;
}
这是有参数的
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*///除了基本数据类型,其他类型的参数都需要标上方向类型:in(输入), out(输出), inout(输入输出)
@Override
public java.util.List<com.example.yhadmin.aidldemo.bean.Person> getPersonList(java.lang.String name,
int age)
throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List<com.example.yhadmin.aidldemo.bean.Person> _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(name);
_data.writeInt(age);
mRemote.transact(Stub.TRANSACTION_getPersonList, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArrayList(com.example.yhadmin.aidldemo.bean.Person.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
由上可知,IBookManager 不但继承了 IInterface 接口,同时它自己也还是个接口,所有可以在Binder 中传输的接口都需要继承 IInterface 接口,
AIDL 文件的本质是系统为我们提供了一套快速实现Binder 的工具而已
注意:
1、当客户端发起远程请求时,由于当前线程会被挂起直至服务端进程返回数据,所以如果一个远程方法是很耗时的,则不能在UI 线程中发起此远程请求
2、由于服务端的Binder 方法运行在 Binder 的线程池中,所以 Binder 方法不管是否耗时都应该采用同步的方式去实现,因为它已经运行在一个线程中了
Binder 运行在服务端进程,如果服务端进程由于某种原因异常终止,这个时候我们到服务端的Binder 断裂(称之Binder 死亡),会导致我们的远程调用失败,更关键的是我们不知道Binder 连接已经断裂,就会导致客户端的功能受到影响。为了解决该问题,Binder 中提供了两个配对的方法
linkToDeath 和 unlinkToDeath
Binder 的两个很重要的方法:
linkToDeath:通过该方法可以给Binder 设置一个死亡代理,当Binder 死亡时,我们就会收到通知,此时我们就可以重新发起连接请求从而恢复连接
unlinkToDeath:Binder 解除之前的绑定
首先,声明一个 DeathRecipient 对象,DeathRecipient 是一个接口(在IBinder内部),其内部只有一个 binderDied 方法,我们需要实现这个方法,当Binder 死亡的时候,系统就会回调 binderDied 方法,然后我们就可以移除之前绑定的 binder 代理并重新绑定远程服务
mBookManager = new IBookManager.Stub() {
@Override
public List<Book> getBookList()
throws RemoteException
{
return null;
}
@Override
public void addBook(Book book)
throws RemoteException
{
}
};
mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
if (mBookManager == null){
return;
}
mBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);//解除绑定
mBookManager=null;
//TODO:这里重新绑定远程服务
}
};
在客户端绑定远程服务成功后,给 binder 设置死亡代理
IMessageBoxManager.Sub.asInterface(binder);
binder.linkToDeath(mDeathRecipient,0);//0为标记位,
经过上面的两个步骤,就给我们的Binder 设置了死亡代理,当Binder 死亡的时候我们就可以接收到通知了,同时还可通过 Binder 的 isBinderAlive 方法也可判断 Binder 是否死亡
错误:
未引入Person 包导致,导入Bean 后正常
import com.example.yhadmin.aidldemo.bean.Person;