6 Java注册系统服务
Java获取的ServiceManager代理是ServiceManagerProxy,
ServiceManagerProxy的addService如下,
public void addService(String name, IBinder service, boolean allowIsolated)
throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name);
data.writeStrongBinder(service);
data.writeInt(allowIsolated ? 1 : 0);
mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
reply.recycle();
data.recycle();
}
BinderProxy是Binder的内部类, mRemote变量指向BinderProxy对象。因此调用将数据打包后调用
BinderProxy的transact方法,
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
Binder.checkParcel(this, code, data, "Unreasonably large binder buffer");
return transactNative(code, data, reply, flags);
}
transactNative对应的是android_util_Binder.cpp的android_os_BinderProxy_transact方法,
static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
jint code, jobject dataObj, jobject replyObj, jint flags)
{
...
//java Parcel转为native Parcel
Parcel* data = parcelForJavaObject(env, dataObj);
Parcel* reply = parcelForJavaObject(env, replyObj);
...
//gBinderProxyOffsets.mObject中保存的是new BpBinder(0)对象
IBinder* target = (IBinder*)
env->GetLongField(obj, gBinderProxyOffsets.mObject);
...
//此处便是BpBinder::transact(), 经过native层,进入Binder驱动程序
status_t err = target->transact(code, *data, reply, flags);
...
return JNI_FALSE;
}
Java层的BinderProxy.transact()最终交由Native层BpBinder的BpBinder::transact()完成。
BpBinder的transact方法在上个章节中已经论述了。
由此看出,Java注册系统服务最后也会走native方法。