Java 服务代理对象的获取过程
2018-07-23 本文已影响0人
ColdWave
Java 服务代理对象的获取过程
// ./packages/experimental/Freg/src/shy/luo/freg/Freg.java
public class Freg extends Activity implements onClickListener {
......
private IFregService fregService = null;
......
@Override
public void onCreate(Bundle savedInstanceState) {
......
fregService = IFregService.Stub.asInterface(ServiceManager.getService("freg"));
......
}
......
}
getService
public final class ServiceManager {
public static IBinder getService(String name) {
try {
IBinder service = sCache.get(name);
if (service != null) {
return service;
} else {
return Binder.allowBlocking(getIServiceManager().getService(name));
}
} catch (RemoteException e) {
Log.e(TAG, "error in getService", e);
}
return null;
}
}
sCache 用来保存已经获得的 JavaBinderProxy.
class ServiceManagerProxy implements IServiceManager {
public ServiceManagerProxy(IBinder remote) {
mRemote = remote;
}
public IBinder asBinder() {
return mRemote;
}
public IBinder getService(String name) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name);
mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);
IBinder binder = reply.readStrongBinder();
reply.recycle();
data.recycle();
return binder;
}
}
class Parcel {
......
/**
* Read an object from the parcel at the current dataPosition().
*/
public final IBinder readStrongBinder() {
return nativeReadStrongBinder(mNativePtr);
}
......
}
static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jclass clazz, jlong nativePtr)
{
Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
if (parcel != NULL) {
return javaObjectForIBinder(env, parcel->readStrongBinder());
}
return NULL;
}
- parcel->readStrongBinder 获得 BpBinder.
- javaObjectForIBinder 将 BpBinder 转换成 Java BinderProxy
asInterface
public interface IFregService extends android.os.IInterface {
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements
android.os.IFregService {
private static final java.lang.String DESCRIPTOR = "android.os.IFregService";
/** Construct the stub at attach it to the interface. */
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an android.os.IFregService interface,
* generating a proxy if needed.
*/
public static android.os.IFregService 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 android.os.IFregService))) {
return ((android.os.IFregService) iin);
}
return new android.os.IFregService.Stub.Proxy(obj);
}
}
}
asInterface 中 obj 参数是 Java BinderProxy, 所以 queryLocalInterface 返回 null.然后就会创建 android.os.IFregService.Stub.Proxy.