Vold: Volume Daemon,用于管理和控制Android平台外部存储设备的后台进程,这些管理和控制,包括SD卡的插拔事件检测/SD卡挂载/卸载/格式化等.
9.0以前framework java层(StorageManagerService)和native层(Vold)的通信是socket,9.0以后使用binder通信.本文通过SD卡挂载流程,分析binder在vold服务中的使用.
vold服务在开机的时候会启动.定义于system/vold/vold.rc文件中:
service vold /system/bin/vold \
--blkid_context=u:r:blkid:s0 --blkid_untrusted_context=u:r:blkid_untrusted:s0 \
--fsck_context=u:r:fsck:s0 --fsck_untrusted_context=u:r:fsck_untrusted:s0
class core
ioprio be 2
writepid /dev/cpuset/foreground/tasks
shutdown critical
group reserved_disk
被init进程启动后,将调用system/vold/main.cpp中的main函数,然后初始化VolumeManager,NetlinkManager等等.初始化Vold服务.
在看下StorageManagerService的初始化.StorageManagerService由SystemServer启动,我们简单看看它的启动流程:
//调用SystemServiceManager的startService
mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
最终的实现如下:
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
//调用服务的onStart方法.
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
//StorageManagerService的onStart方法如下:
@Override
public void onStart() {
//创建StorageManagerService
mStorageManagerService = new StorageManagerService(getContext());
//将StorageManagerService注册到ServiceManager中
publishBinderService("mount", mStorageManagerService);
//调用StorageManagerService的start方法
mStorageManagerService.start();
}
private void start() {
connect();
}
//主要建立和Vold的通信,获取mVold对象,与Vold进程通信.
private void connect() {
IBinder binder = ServiceManager.getService("storaged");
if (binder != null) {
try {
//为binder对象设置死亡代理。当binder死亡后重新建立连接.
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "storaged died; reconnecting");
mStoraged = null;
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
mStoraged = IStoraged.Stub.asInterface(binder);
} else {
Slog.w(TAG, "storaged not found; trying again");
}
binder = ServiceManager.getService("vold");
if (binder != null) {
try {
//为binder对象设置死亡代理。当binder死亡后重新建立连接.
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "vold died; reconnecting");
mVold = null;
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
//通过binder机制,获取mVold对象(mVold就是IVold对象,这是一个代理类,具体实现在VoldNativeService.cpp),从而和Vold进程进行通信.
mVold = IVold.Stub.asInterface(binder);
try {
//mListener是IVoldListener的具体实现,当vold进程中相关事件改变通过IVoldListener这个代理,通知StorageManagerService处理.
mVold.setListener(mListener);
} catch (RemoteException e) {
mVold = null;
Slog.w(TAG, "vo