首先保证你的应用能够获取system权限:android:sharedUserId="android.uid.system";
然后申请权限:
调用以下代码完成格式化:
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("get