作者: 刘望舒
原文:http://liuwangshu.cn/framework/binder/7-javabinder-addservice.html
前言
在http://liuwangshu.cn/framework/binder/3-addservice.html 这篇文章中,我介绍的是Native Binder中的系统服务的注册过程,这一过程的核心是ServiceManager,而在Java Binder中,也有一个ServiceManager,只不过这个ServiceManager是Java文件。
既然要将系统服务注册到ServiceManager,那么需要选择一个系统服务为例,这里以常见的AMS为例。
1.将AMS注册到ServiceManager
在AMS的setSystemProcess方法中,会调用ServiceManager的addService方法,如下所示。frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);//1
....
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
...
}
注释1处的Context.ACTIVITY_SERVICE
的值为"activity",作用就是将AMS注册到ServiceManager中。接着来看
ServiceManager的addService方法。frameworks/base/core/java/android/os/ServiceManager.java
public static void addService(String name, IBinder service, boolean allowIsolated,int dumpPriority) {
try {
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
主要分析getIServiceManager方法返回的是什么,代码如下所示。frameworks/base/core/java/android/os/ServiceManager.java
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
return sServiceManager;
}
讲到这里,已经积累了几个点需要分析,分别是:
BinderInternal.getContextObject()
ServiceManagerNative.asInterface()
getIServiceManager().addService()
现在我们来各个击破它们。
1.1 BinderInternal.getContextObject()
Binder.allowBlocking的作用是将BinderProxy的sWarnOnBlocking值置为false。主要来分析BinderInternal.getContextObject()做了什么,这个方法是一个Native方法,找到它对应的函数:frameworks/base/core/jni/android_util_Binder.c