Android的Service Binder机制

IMyService myService = IMyService .Stub.asInterface(ServiceManager.getService("myservice"));

// 可以去IMyService的实现中找到asInterface方法的实现(IMyService.java由IMyService.aidl生成):
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements  com.android.my.IMyService
{
private static final java.lang.String DESCRIPTOR = "com.android.my.IMyService";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
 * Cast an IBinder object into an com.android.my.IMyService interface,
 * generating a proxy if needed.
 */

public static com.android.my.IMyService asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof my.IMyService))) {
return ((my.IMyService)iin);
}
return new my.IMyService.Stub.Proxy(obj);
}

// 可见,ServiceManager中注册的是IBinder,可以理解为句柄,传入asInterface后,通过接口的描述生成相应接口,接着返回代理的接口对象。

你可能感兴趣的:(android)