近期在忙一个硬件设备项目,项目背景下需要持续高频写入外置sd卡,由于过于碎片化操作sd卡,长时间会导致sd卡开启自我保护,无法继续使用。按厂商建议,需要格式化sd卡才能继续使用。
方案一
android系统本身未提供通用格式化sd卡的能力,经调研,需要将应用升级为系统应用,加入权限后,可以调用系统服务,格式化sd卡。
String path = "/storage/sdcard1";
for (StorageVolume storageVolume : service.getVolumeList()) {
Method method = storageVolume.getClass().getMethod("getPath");
if (path.equals((String)method.invoke(storageVolume))) {
Intent intent = new Intent(ExternalStorageFormatter.FORMAT_ONLY);
intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME);
intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, storageVolume);
InsContext.getContext().startService(intent);
}
}
方案二
但在调试中发现,由于硬件厂商对系统的定制化,以上方案在实现时,无法格式化指定sd卡sdcard1,一直默认格式化内部存储sdcard0。
在研读android源码后,可以仿照源码方案实现。同样需要系统应用级别和权限。
public static void formatSD() {
Log.i(TAG, "进入格式化SD卡流程");
final IMountService service = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
if (service != null) {
// 异步开始格式化 sd 卡
ExecutorUtils.INSTANCE.post(() -> {
try {
Log.i(TAG, "格式化SD卡开始");
android.os.storage.StorageManager storageManager = (android.os.storage.StorageManager) InsContext.getContext().getSystemService(Context.STORAGE_SERVICE);
// sd卡状态变化监听,因为umount需要时间,只有等sd卡umount结束后才能格式化,否则会失败
StorageEventListener storageEventListener = new StorageEventListener() {
@Override
public void onStorageStateChanged(String path, String oldState, String newState) {
Log.i(TAG, "Received storage state changed notification that " +
path + " changed state from " + oldState + " to " + newState);
try {
formatSDProcess(service, storageManager);
} catch (Exception e) {
// Intentionally blank - there's nothing we can do here
Log.w(TAG, "Unable to invoke IMountService.formatMedia()");
Log.e(TAG, e.getMessage());
}
}
};
// 先注册监听
Method registerListener = storageManager.getClass().getMethod("registerListener", StorageEventListener.class);
registerListener.invoke(storageManager, storageEventListener);
formatSDProcess(service, storageManager);
} catch (Exception e) {
// Intentionally blank - there's nothing we can do here
Log.w(TAG, "Unable to invoke IMountService.formatMedia()");
Log.e(TAG, e.getMessage());
}
});
} else {
Log.w(TAG, "Unable to locate IMountService");
}
}
private static void formatSDProcess(IMountService service, android.os.storage.StorageManager storageManager) throws Exception {
String path = com.poi.data.commonability.storage.StorageManager.Companion.getSdcardPath();
Log.i(TAG, "格式化SD卡路径:" + path);
Method getVolumeState = storageManager.getClass().getMethod("getVolumeState", String.class);
String state = (String) getVolumeState.invoke(storageManager, path);
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Log.i(TAG, "unmountVolume:" + path);
service.unmountVolume(path, true, true);
} else {
int ret = service.formatVolume(path);
Log.i(TAG, "formatVolume 结果:" + ret);
if (ret == 0) {
// 格式化成功
// TODO
}
}
}
|