Android源码里有不少关于代理模式的实现,比如源码的[ActivityManagerProxy](https://www.androidos.net.cn/android/5.0.1_r1/xref/frameworks/base/core/java/android/app/ActivityManagerNative.java) 代理类, 其具体代理的是[ActivityManagerNative](https://www.androidos.net.cn/android/5.0.1_r1/xref/frameworks/base/core/java/android/app/ActivityManagerNative.java) 的子类[ActivityManagerService](https://www.androidos.net.cn/android/5.0.1_r1/xref/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java)。
[ActivityManager](https://www.androidos.net.cn/android/5.0.1_r1/xref/frameworks/base/core/java/android/app/ActivityManager.java)是Android中管理和维护Activity的相关信息的类,为了隔离它与ActivityManagerService,有效降低二者的耦合,在这中间使用了ActivityManagerProxy代理类,所有对ActivityManagerService的访问都转换成对代理类的访问,这样ActivityManager就与ActivityManagerService解耦了。
![](https://box.kancloud.cn/a4d9e0c5cc30fe5a71a87f4d37285151_268x84.jpg)
![](https://box.kancloud.cn/a555c35a8896719796116df8b3beb40a_248x82.jpg)
**ActivityManagerNative.java**
~~~
public abstract class ActivityManagerNative extends Binder implements IActivityManager{
................................
}
~~~
**IActivityManager.java**
~~~
public interface IActivityManager extends IInterface {
....................
}
~~~
**ActivityManagerService.java**
~~~
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
.....................
}
~~~
**ActivityManager.java**
~~~
public class ActivityManager {
.................
}
~~~
下面我们以API 21(Android 5.0.0_r7)来学习Android源码中的代理模式
ActivityManagerProxy 这个类, 该类与ActivityManagerNative 这个类处于同一文件中。
~~~
class ActivityManagerProxy implements IActivityManager{
..................
}
~~~
ActivityManagerProxy 实现了IActivityManager 接口,该接口定义了一些Activity 相关的接口方法, 其中有一些我们在应用开发中也时常接触到。
**IActivityManager.java**
~~~
package android.app;
/**
* System private API for talking with the activity manager service. This
* provides calls from the application back to the activity manager.
*
* {@hide}
*/
public interface IActivityManager extends IInterface {
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
ProfilerInfo profilerInfo, Bundle options) throws RemoteException;
...............
public Intent registerReceiver(IApplicationThread caller, String callerPackage,
IIntentReceiver receiver, IntentFilter filter,
String requiredPermission, int userId) throws RemoteException;
public void unregisterReceiver(IIntentReceiver receiver) throws RemoteException;
..............
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, int userId) throws RemoteException;
public int stopService(IApplicationThread caller, Intent service,
String resolvedType, int userId) throws RemoteException;
.............
public int bindService(IApplicationThread caller, IBinder token,
Intent service, String resolvedType,
IServiceConnection connection, int flags, int userId) throws RemoteException;
................
public int checkPermission(String permission, int pid, int uid)
throws RemoteException;
...............
public void overridePendingTransition(IBinder token, String packageName,
int enterAnim, int exitAnim) throws RemoteException;
...............
}
~~~
IActivityManager 这个接口类就相当于代理模式中的抽象主题,那么真正的实现主题是谁呢?就是上面我们所提到过的继承于ActivityManagerNative 的ActivityManagerService 类,这几个类之间的大致关系如图所示。
:-: ![](https://box.kancloud.cn/f720f39eb9bc2b2165922767d5e27b0f_643x498.png)
IActivityManager的结构关系
通过UML类图可以清晰地看到ActivityManagerProxy和ActivityManagerNative都实现了接口IActivityManager,严格来说, **ActivityManagerProxy 就是代理部分**,而ActivityManagerNative 就是真实部分,但**ActivityManagerNative 是个抽象类,其并不处理过多的具体逻辑, 大部分具体逻辑的实现都由其子类ActivityManagerService 承担**,这就是为什么我们说真实部分应该为ActivityManagerService 而非ActivityManagerNative。**ActivityManagerService 是系统级的Service 并且运行于独立的进程空间中,可以通过ServiceManger 来获取它。而ActivityManagerProxy 也运行于自己所处的进程空间中,两者并不相同,因此ActivityManager Proxy 与ActivityManagerService 的通信必定是通过跨进程来进行的,而由上述的类图我们也可以了解到,这里跨进程的实现是基于Android 的Binder机制**,同时通过上面我们对代理模式的4 种适用情景可以判断,**此处源码所实现的代理实质为远程代理**。**ActivityManagerProxy 在实际的逻辑处理中并未过多地被外部类使用,因为在Android 中管理与维护Activity 相关信息的类是另外一个叫做ActivityManager 的类**, **ActivityManager 虽说管理着Activity 的信息,但是实质上其大多数逻辑都由ActivityManagerProxy 承担**,这里以其中的getAppTasks 方法为例,在ActivityManager 中getAppTasks 方法的逻辑如下。
**ActivityManager:getAppTasks()**
~~~
public List<ActivityManager.AppTask> getAppTasks() {
ArrayList<AppTask> tasks = new ArrayList<AppTask>();
List<IAppTask> appTasks;
try {
appTasks = ActivityManagerNative.getDefault().getAppTasks(mContext.getPackageName());
} catch (RemoteException e) {
// System dead, we will be dead too soon!
return null;
}
int numAppTasks = appTasks.size();
for (int i = 0; i < numAppTasks; i++) {
tasks.add(new AppTask(appTasks.get(i)));
}
return tasks;
}
~~~
主要只是简单地调用了ActivityManagerNative的getDefault 方法获取一个IActivityManager 类型的对象,然后通过该对象再调用其getAppTasks方法,注意,这里结合代理模式理解。而ActivityManagerNative的getDefault 方法只是单纯地返回了。
**ActivityManagerNative:getDefault()**
~~~
static public IActivityManager getDefault() {
return gDefault.get();
}
~~~
这个gDefault 又是做什么的呢?具体如下代码所示。
**ActivityManagerNative.getDefault**
~~~
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
~~~
上述代码只是构造了一个Singleton<IActivityManager>类型的gDefault 对象,其中通过`ServiceManager.getService("activity")`获取了一个系统级的Service,而**这个Service 实质上就是ActivityManagerService** ,这里也就完成创建了一个对ActivityManagerService 的Client 代理对象ActivityManagerProxy 的实例。ActivityManagerProxy 中的getAppTasks 方法逻辑就很明确,将数据打包跨进程传递给Server 端ActivityManagerService 处理并返回结果。
**ActivityManagerProxy:getAppTasks**
~~~
public List<IAppTask> getAppTasks(String callingPackage) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeString(callingPackage);
mRemote.transact(GET_APP_TASKS_TRANSACTION, data, reply, 0);
reply.readException();
ArrayList<IAppTask> list = null;
int N = reply.readInt();
if (N >= 0) {
list = new ArrayList<IAppTask>();
while (N > 0) {
IAppTask task = IAppTask.Stub.asInterface(reply.readStrongBinder());
list.add(task);
N--;
}
}
data.recycle();
reply.recycle();
return list;
}
~~~
再来看看ActivityManagerService 中对getAppTasks 方法的逻辑处理
**ActivityManagerService:getAppTasks**
~~~
@Override
public List<IAppTask> getAppTasks(String callingPackage) {
int callingUid = Binder.getCallingUid();
long ident = Binder.clearCallingIdentity();
synchronized(this) {
ArrayList<IAppTask> list = new ArrayList<IAppTask>();
try {
if (localLOGV) Slog.v(TAG, "getAppTasks");
final int N = mRecentTasks.size();
for (int i = 0; i < N; i++) {
TaskRecord tr = mRecentTasks.get(i);
// Skip tasks that do not match the caller. We don't need to verify
// callingPackage, because we are also limiting to callingUid and know
// that will limit to the correct security sandbox.
if (tr.effectiveUid != callingUid) {
continue;
}
Intent intent = tr.getBaseIntent();
if (intent == null ||
!callingPackage.equals(intent.getComponent().getPackageName())) {
continue;
}
ActivityManager.RecentTaskInfo taskInfo =
createRecentTaskInfoFromTaskRecord(tr);
AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid);
list.add(taskImpl);
}
} finally {
Binder.restoreCallingIdentity(ident);
}
return list;
}
}
~~~
不了解Android 中的跨进程通信,也许对上述代码理解起来会比较困难。