6.2.2 调用ServiceManagerNative.asInterface方法
BinderInternal. getContextObject()方法执行完毕后返回ServiceManager中,继续执行Service ManagerNative.asInterface,其代码如下:
sServiceManager=ServiceManagerNative.asInterface(
BinderInternal.getContextObject());
已知BinderInternal.getContextObject()返回的是BinderProxy,因此上述代码等价于:
sServiceManager=ServiceManagerNative.asInterface(new BinderProxy());
asInterface定义于frameworks/base/core/java/android/os/ServiceManagerNative.java中,其代码如下:
static public IServiceManager asInterface(IBinder obj)
{
/由上文分析可知,参数obj便是BinderProxy,其queryLocalInterface方法直接返回null/
IServiceManager in=
(IServiceManager)obj.queryLocalInterface(descriptor);
if(in!=null){
return in;
}
/最终返回的其实是ServiceManagerProxy对象/
return new ServiceManagerProxy(obj);
}
这里的参数obj是一个BinderProxy对象,它的queryLocalInterface函数返回null。最终以这个BinderProxy对象为参数创建一个ServiceManagerProxy对象并返回,因此以下代码:
sServiceManager=ServiceManagerNative.asInterface(new BinderProxy());
等价于:
sServiceManager=new ServiceManagerProxy(new BinderProxy());
这里涉及很多类和接口之间的依赖关系,需要从其继承层次理清其关系,如图6-4所示。
图 6-4 类和接口之间的依赖关系
ServiceManagerProxy定义于ServiceManagerNative.java中,代码如下:
class ServiceManagerProxy implements IServiceManager{
public ServiceManager Proxy(IBinder remote){
mRemote=remote;//Service ManagerProxy中保存了BinderProxy的引用
}
public IBinder asBinder(){//提供了asBinder返回该BinderProxy的引用
return mRemote;
}
……
//省略部分代码
private IBinder mRemote;
}
ServiceManagerProxy将BinderProxy类型的remote参数存入成员变量mRemote,并通过asBinder()方法返回该BinderProxy对象。
ServiceManagerNative. asInterface的作用是:在Java层构造ServiceManagerProxy对象,在该对象的成员变量mRemote中保存了Java层的BpBinder对象,该BpBinder对象关联了Native层的BpBinder对象,在本例中该BpBinder对象的handler值为0。
注意 ServiceManagerNative的asInterface方法与Native层的interface_cast宏定义(第5章)的作用是一样的。