class MountService extends IMountService.Stub
implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {}
在frameworks\base\core\java\android\os\storage下找到IMountService.java,竟然不是.aidl。原来在android2.x时代是aidl,现在直接就是java
看IMountService 就学习一下Binder这个知识:
public interface IMountService extends IInterface {
/* Local-side IPC implementation stub class. /
public static abstract class Stub extends Binder implements IMountService {
private static class Proxy implements IMountService {
private final IBinder mRemote;
Proxy(IBinder remote) {
mRemote = remote;
}
public IBinder asBinder() {
return mRemote;
}
public String getInterfaceDescriptor() {
return DESCRIPTOR;
}
/**
* Registers an IMountServiceListener for receiving async
* notifications.
*/
public void registerListener(IMountServiceListener listener) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((listener != null ? listener.asBinder() : null));
mRemote.transact(Stub.TRANSACTION_registerListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
。。。
public static IMountService asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (iin != null && iin instanceof IMountService) {
return (IMountService) iin;
}
return new IMountService.Stub.Proxy(obj);
}
。。。
}
我们正常使用远端服务时经常使用这个方法asInterface。
这个位置我不清楚应该从第一处还是第二处返回。关于第一处的信息如下,待分析。
public Stub() {
attachInterface(this, DESCRIPTOR);
}
attachInterface这个方法里才会设置此Binder所属Interface
public void attachInterface(IInterface owner, String descriptor) {
mOwner = owner;
mDescriptor = descriptor;
}
从第二处返回的话则创建一个Proxy,他的每一个方法如下:
public void registerListener(IMountServiceListener listener) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((listener != null ? listener.asBinder() : null));
mRemote.transact(Stub.TRANSACTION_registerListener, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
其中mRemote即return new IMountService.Stub.Proxy(obj);中的obj,此处应该就是IMountService.Stub类型的对象,
来看看IMountService.Stub的onTransact方法
@Override
public boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_registerListener: {
data.enforceInterface(DESCRIPTOR);
IMountServiceListener listener;
listener = IMountServiceListener.Stub.asInterface(data.readStrongBinder());
registerListener(listener);
reply.writeNoException();
return true;
}
。。。
}
调用他的registerListener方法,这是IMountService.Stub实现类的本地方法,即MountService方法
本文深入探讨了Android中Binder机制的实现原理,并通过MountService这一具体案例进行详细解析。介绍了Binder如何实现进程间通信(IPC),以及MountService作为Binder服务的具体实现细节。
1220

被折叠的 条评论
为什么被折叠?



