下面直接从ServiceManager的addService看起
ServiceManager.java
public static void addService(String name, IBinder service) {
try {
getIServiceManager().addService(name, service, false);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
// Find the service manager
sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
return sServiceManager;
}
1. BinderInternal.getContextObject()
BinderInternal.java
public static final native IBinder getContextObject();
对应的是一个native方法
android_util_Binder.cpp
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
{
sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
return javaObjectForIBinder(env, b);
}
通过文章Android Binder之ServiceManager注册服务解析1可知,ProcessState::self()->getContextObject(NULL)得到的是一个BpBinder对象。
下面具体看看javaObjectForIBinder方法。是一个native方法,方法的实现在android_util_Binder.cpp中
jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
if (val == NULL) return NULL;
if (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;
}
// 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);
// Someone else's... do we know about it?
jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
if (object != NULL) {
jobject res = jniGetReferent(env, object);
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对象,并将其注册到native BpBinder对象的ObjectManager对象中
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.
// 把native层的BpBinder指针保存在BinderProxy对象的成员字段mObject中
env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());
val->incStrong((void*)javaObjectForIBinder);
// 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));
// 将新创建的BinderProxy对象注册到BpBinder的ObjectManager对象中
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;
}
javaObjectForIBinder方法的作用就是将native层的BpBinder对象封装成一个java层的BpProxy对象返回给java层的调用者。这样就是实现了java层对native层binder的操作了。
具体操作如下:
1、创建一个java层的BinderProxy对象
2、通过JNI将BinderProxy与native层的BpBinder对象关联起来。
上面返回的就是一个BinderProxy对象,下面看看ServiceManagerNative的asInterface
2. ServiceManagerNative.asInterface(BinderInternal.getContextObject())
ServiceManagerNative.java
static public IServiceManager asInterface(IBinder obj)
{
if (obj == null) {
return null;
}
IServiceManager in =
(IServiceManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ServiceManagerProxy(obj);
}
上面传入的obj对象是BinderProxy对象,下面看看BinderProxy的queryLocalInterface方法。
Binder.java
final class BinderProxy implements IBinder {
public IInterface queryLocalInterface(String descriptor) {
return null;
}
}
可以看到返回的为null,所以最终返回new ServiceManagerProxy(obj)
public ServiceManagerProxy(IBinder remote) {
mRemote = remote;
}
所以,mRemote对应的就是BinderProxy对象。
所以上面其实最终调用的是ServiceManagerProxy的addService方法。
ServiceManagerNative$ServiceManagerProxy.java
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();
}
因为mRemote对应的就是BinderProxy对象,下面看看BinderProxy的transact方法。
final class BinderProxy implements IBinder {
public native boolean transact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException;
}
可以看到这是一个native方法。在android_util_Binder.cpp中
final class BinderProxy implements IBinder {
public native boolean transact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException;
}
可以看到这是一个native方法。在android_util_Binder.cpp中
static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
{
if (dataObj == NULL) {
jniThrowNullPointerException(env, NULL);
return JNI_FALSE;
}
// 将java层的Parcel对象转换为Native的Parcel对象
Parcel* data = parcelForJavaObject(env, dataObj);
if (data == NULL) {
return JNI_FALSE;
}
// 将java层的Parcel对象转换为Native的Parcel对象
Parcel* reply = parcelForJavaObject(env, replyObj);
if (reply == NULL && replyObj != NULL) {
return JNI_FALSE;
}
// 得到之前在BinderProxy的mObject字段中存放的Native层的BpBinder对象
IBinder* target = (IBinder*)
env->GetIntField(obj, gBinderProxyOffsets.mObject);
if (target == NULL) {
jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
return JNI_FALSE;
}
ALOGV("Java code calling transact on %p in Java object %p with code %d\n",
target, obj, code);
#if ENABLE_BINDER_SAMPLE
// Only log the binder call duration for things on the Java-level main thread.
// But if we don't
const bool time_binder_calls = should_time_binder_calls();
int64_t start_millis;
if (time_binder_calls) {
start_millis = uptimeMillis();
}
#endif
//printf("Transact from Java code to %p sending: ", target); data->print();
// 通过Native层的BpBinder对象进行调用,后面的过程在之前讲述过
status_t err = target->transact(code, *data, reply, flags);
//if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
#if ENABLE_BINDER_SAMPLE
if (time_binder_calls) {
conditionally_log_binder_call(start_millis, target, code);
}
#endif
if (err == NO_ERROR) {
return JNI_TRUE;
} else if (err == UNKNOWN_TRANSACTION) {
return JNI_FALSE;
}
signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
return JNI_FALSE;
}