讲Android Binder机制
的文章非常多,这篇文章主要是理一下我对Binder
的理解。本文不是一篇介绍Binder
的文章,也不是一篇探讨Binder
实现的文章。
本文会以AndroidStudio
根据aidl接口
自动产生的java文件
来看Binder
,进而来理解Binder机制
。
其实Android的Binder机制类似于:RPC(远程过程调用)。如果你理解它,相信
Binder
机制就更容易理解了。
首先我们使用AndroidStudio
来定义一个aidl
接口:
interface IUserManager {
int getUserAge(in String userName);
}
然后我们来直接看一个由AndroidStudio
根据自定义的aidl
接口IUserManager
产生的IUserManager.java
文件。
这个文件我们来分3个部分看:
IUserManager接口结构
public interface IUserManager extends android.os.IInterface {
public static abstract class Stub extends android.os.Binder implements com.susion.demo.aidl.IUserManager {..}
public int getUserAge(java.lang.String userName) throws android.os.RemoteException;
}
这个接口的结构还是很简单的:
- 它继承自
android.os.IInterface
。 - 定义了一个待实现的方法
int getUserAge()
- 定义了一个
Stub
类。这个类继承自Binder
,并实现了IUserManager
接口。
int getUserAge()
这个方法就是我们IUserManager接口
的方法。而android.os.IInterface
是什么呢?先看一下它在源码中的定义:
/**
* Base class for Binder interfaces. When defining a new interface,
* you must derive it from IInterface.
*/
public interface IInterface
{
/**
* Retrieve the Binder object associated with this interface.
* You must use this instead of a plain cast, so that proxy objects
* can return the correct result.
*/
public IBinder asBinder(); //IBinder是Binder的抽象接口
}
即他是所有Binder
都要实现的接口, 为什么呢?举一个我们都熟悉的场景 :
比如ApplicationThread
,ActivityManagerService
(运行在服务端进程)就可以通过它来调用我们客户端的方法。我们会把这些方法抽象为一个接口(IApplicationThread
),这个接口可以理解为我们告诉服务端,你可以对客户端执行哪些操作。
我们还知道ApplicationThread
其实他就是一个Binder
。所以这两者一结合就可以这么说ApplicationThread
: 客户端提供给服务端一个Binder
,通过这个Binder
服务端可以对客户端做一些操作,这些操作具体定义在