Android5.x+ 格式化外部存储(u盘, sdcard)的方法

时间:2021-12-07 15:11:15

首先保证你的应用能够获取system权限:android:sharedUserId="android.uid.system";

然后申请权限:

<uses-permission android:name="android.permission.MASTER_CLEAR"/>
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>

调用以下代码完成格式化:

public void diskFormat() {    ComponentName formatter = new ComponentName("android", "com.android.internal.os.storage.ExternalStorageFormatter");    Intent intent = new Intent("com.android.internal.os.storage.FORMAT_ONLY"); // ExternalStorageFormatter.FORMAT_ONLY    intent.setComponent(formatter);    Parcelable sv = getStoragePath(mContext);    intent.putExtra("storage_volume", sv);  // StorageVolume.EXTRA_STORAGE_VOLUME    mContext.startService(intent);}// 获取 StorageVolume 对象private Parcelable getStoragePath(Context mContext) {    StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);    Class<?> storageVolumeClazz = null;    try {        storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");        Method getPath = storageVolumeClazz.getMethod("getPath");        Method isRemovable = storageVolumeClazz.getMethod("isRemovable");        Object result = getVolumeList.invoke(mStorageManager);        final int length = Array.getLength(result);        for (int i = 0; i < length; i++) {            Object storageVolumeElement = Array.get(result, i);            String path = (String) getPath.invoke(storageVolumeElement);            boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);            if (removable && path.equals(mPreferUsbPath)) {                return (Parcelable) storageVolumeElement;            }        }    }  catch (Exception e) {        e.printStackTrace();    }    return null;}

mPreferUsbPath是你需要格式化的外部存储路径,按实际替换即可。

一般MountService会默认将外部存储格式化为 EXT3 文件系统格式,当然根据定制ROM配置文件的不同也可能为其他格式。