在SystemServer中会调用下面进行ActivityManagerService的注册
context = ActivityManagerService.main(factoryTest);
ActivityManagerService.setSystemProcess();
在main方法中会创建一个ActivityManagerService对象,对应的是mSelf变量
下面看看setSystemProcess函数
public static void setSystemProcess() {
try {
ActivityManagerService m = mSelf;
// 将ActivityManagerService服务注册到ServiceManager中
ServiceManager.addService(Context.ACTIVITY_SERVICE, m, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, m.mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(m));
ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
ServiceManager.addService("dbinfo", new DbBinder(m));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(m));
}
ServiceManager.addService("permission", new PermissionController(m));
ApplicationInfo info =
mSelf.mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS);
mSystemThread.installSystemApplicationInfo(info);
synchronized (mSelf) {
ProcessRecord app = mSelf.newProcessRecordLocked(info,
info.processName, false);
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mSelf.mProcessStats);
mSelf.mProcessNames.put(app.processName, app.uid, app);
synchronized (mSelf.mPidsSelfLocked) {
mSelf.mPidsSelfLocked.put(app.pid, app);
}
mSelf.updateLruProcessLocked(app, false, null);
mSelf.updateOomAdjLocked();
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}
关于ServiceManager的整个执行过程在Android java层binder解析1中已经讲解过了。
下面重点看看ServiceManagerProxy.java中的addService方法中的data.writeStrongBinder(service);
其中,data就是一个Parcel对象,service就是ActivityManagerService对象
Parcel.java
public final void writeStrongBinder(IBinder val) {
nativeWriteStrongBinder(mNativePtr, val);
}
private static native void nativeWriteStrongBinder(int nativePtr, IBinder val);
下面看看android_os_Parcel.cpp中的nativeWriteStrongBinder方法
static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jclass clazz, jint nativePtr, jobject object)
{
Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
if (parcel != NULL) {
const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));
if (err != NO_ERROR) {
signalExceptionForError(env, clazz, err);
}
}
}
最主要的就是ibinderForJavaObject 这个函数,继续跟踪代码:
sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
{
if (obj == NULL) return NULL;
// mClass指向Java层中的Binder class
// 下面判断obj是否为一个Binder class
// obj对应的就是ActivityManagerService,它就是一个Binder class
if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
// 得到obj对象中的mObject字段,它对应的是一个JavaBBinderHolder对象
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
env->GetIntField(obj, gBinderOffsets.mObject);
//get() 返回一個JavaBBinder,继承自BBinder
return jbh != NULL ? jbh->get(env, obj) : NULL;
}
//mClass 指向Java层的BinderProxy class
// 下面判断obj是否为一个BinderProxy class
if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
//返回一个BpBinder,mObject是它的地址值
return (IBinder*)
env->GetIntField(obj, gBinderProxyOffsets.mObject);
}
ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
return NULL;
}
上面的操作就是,如果java层的obj是Binder类,则首先获得JavaBBinderHolder对象,然后调用它的get()函数,得到一个JavaBBinder对象进行返回
如果obj是BinderProxy类,则返回的是Native层的BpBinder对象
从上面我们可以知道,addService添加到Parcel中的并不是ActivityManagerService本身,而且一个JavaBBinder对象,所以最终传递到Binder驱动的就是这个JavaBBinder对象。
下面我们可以总结:
1、java层的Binder通过mObject指向一个Native层的JavaBinderHolder对象。
2、Native层的JaveBinderHolder对象通过mBinder成员指向一个Native层的JavaBBinder对象。
3、Native层的JavaBBinder对象又通过mObject变量指向Java层的Binder对象。
上面我们知道了最终传递到Binder驱动的就是这个JavaBBinder对象,所以当我们进行远程调用的时候,最终会调用到JavaBBinder的onTransact方法
android_util_Binder.cpp -> JavaBBinder::onTransact()
virtual status_t onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
{
JNIEnv* env = javavm_to_jnienv(mVM);
ALOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
IPCThreadState* thread_state = IPCThreadState::self();
const int strict_policy_before = thread_state->getStrictModePolicy();
thread_state->setLastTransactionBinderFlags(flags);
//printf("Transact from %p to Java code sending: ", this);
//data.print();
//printf("\n");
// mObject对应的就是ActivityManagerService对象,这里就是调用它的execTransact()方法
jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
code, (int32_t)&data, (int32_t)reply, flags);
jthrowable excep = env->ExceptionOccurred();
if (excep) {
report_exception(env, excep,
"*** Uncaught remote exception! "
"(Exceptions are not yet supported across processes.)");
res = JNI_FALSE;
/* clean up JNI local ref -- we don't return to Java code */
env->DeleteLocalRef(excep);
}
// Restore the Java binder thread's state if it changed while
// processing a call (as it would if the Parcel's header had a
// new policy mask and Parcel.enforceInterface() changed
// it...)
const int strict_policy_after = thread_state->getStrictModePolicy();
if (strict_policy_after != strict_policy_before) {
// Our thread-local...
thread_state->setStrictModePolicy(strict_policy_before);
// And the Java-level thread-local...
set_dalvik_blockguard_policy(env, strict_policy_before);
}
jthrowable excep2 = env->ExceptionOccurred();
if (excep2) {
report_exception(env, excep2,
"*** Uncaught exception in onBinderStrictModePolicyChange");
/* clean up JNI local ref -- we don't return to Java code */
env->DeleteLocalRef(excep2);
}
// Need to always call through the native implementation of
// SYSPROPS_TRANSACTION.
if (code == SYSPROPS_TRANSACTION) {
BBinder::onTransact(code, data, reply, flags);
}
//aout << "onTransact to Java code; result=" << res << endl
// << "Transact from " << this << " to Java code returning "
// << reply << ": " << *reply << endl;
return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
}
ActivityManagerService继承了Binder,execTransact()方法在Binder中
private boolean execTransact(int code, int dataObj, int replyObj,
int flags) {
Parcel data = Parcel.obtain(dataObj);
Parcel reply = Parcel.obtain(replyObj);
// theoretically, we should call transact, which will call onTransact,
// but all that does is rewind it, and we just got these from an IPC,
// so we'll just call it directly.
boolean res;
// Log any exceptions as warnings, don't silently suppress them.
// If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
try {
// 最终调用的是onTransact方法
res = onTransact(code, data, reply, flags);
} catch (RemoteException e) {
if ((flags & FLAG_ONEWAY) != 0) {
Log.w(TAG, "Binder call failed.", e);
}
reply.setDataPosition(0);
reply.writeException(e);
res = true;
} catch (RuntimeException e) {
if ((flags & FLAG_ONEWAY) != 0) {
Log.w(TAG, "Caught a RuntimeException from the binder stub implementation.", e);
}
reply.setDataPosition(0);
reply.writeException(e);
res = true;
} catch (OutOfMemoryError e) {
// Unconditionally log this, since this is generally unrecoverable.
Log.e(TAG, "Caught an OutOfMemoryError from the binder stub implementation.", e);
RuntimeException re = new RuntimeException("Out of memory", e);
reply.setDataPosition(0);
reply.writeException(re);
res = true;
}
reply.recycle();
data.recycle();
return res;
}
}
可以看到最终调用的是onTransact方法,即调用ActivityManagerService的onTransact方法,它在ActivityManagerNative中实现
参考文章:
深入理解android 卷3
http://blog.csdn.net/luoshengyang/article/details/6642463