jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val){if(val ==NULL)returnNULL;//如果是 binder 服务端进程调用javaObjectForIBinder //将调用JavaBBinder的object方法返回jobject,//这里jobject的实际Java类型是Binderif(val->checkSubclass(&gBinderOffsets)){// One of our own!
jobject object =static_cast<JavaBBinder*>(val.get())->object();
LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(),
object);return object;}//如果是binder客户端进程,则需要返回Java层的BinderProxy对象// For the rest of the function we will hold this lock, to serialize// looking/creation of Java proxies for native Binder proxies.
AutoMutex _l(mProxyLock);// 如果已有用Java层WeakReference保存的BinderProxy对象,则返回该对象
jobject object =(jobject)val->findObject(&gBinderProxyOffsets);if(object !=NULL){
jobject res = env->CallObjectMethod(object,
gWeakReferenceOffsets.mGet);if(res !=NULL){
ALOGV("objectForBinder %p: found existing %p!\n", val.get(),
res);return res;}
LOGDEATH("Proxy object %p of IBinder %p no longer
in working set!!!", object, val.get());
android_atomic_dec(&gNumProxyRefs);
val->detachObject(&gBinderProxyOffsets);
env->DeleteGlobalRef(object);}//创建BinderProxy对象
object = env->NewObject(gBinderProxyOffsets.mClass,
gBinderProxyOffsets.mConstructor);if(object !=NULL){
LOGDEATH("objectForBinder %p: created new proxy %p !\n",
val.get(), object);// The proxy holds a reference to the native object.//设置BinderProxy对象的mObject字段为本地IBinder对象指针,//本地IBinder对象的实际类型是BpBinder
env->SetIntField(object, gBinderProxyOffsets.mObject,
(int)val.get());
val->incStrong(object);// The native object needs to hold a weak reference back to the// proxy, so we can retrieve //the same proxy if it is still active.
jobject refObject = env->NewGlobalRef(
env->GetObjectField(object, gBinderProxyOffsets.mSelf));//关联gBinderProxyOffsets,故此第20行代码用findObject才能找到
val->attachObject(&gBinderProxyOffsets, refObject,
jnienv_to_javavm(env), proxy_cleanup);// Also remember the death recipients registered on this proxy
sp<DeathRecipientList> drl =new DeathRecipientList;
drl->incStrong((void*)javaObjectForIBinder);
env->SetIntField(object, gBinderProxyOffsets.mOrgue,
reinterpret_cast<jint>(drl.get()));// Note that a new object reference has been created.
android_atomic_inc(&gNumProxyRefs);
incRefsCreated(env);}return object;}