Android5.0以上SDCard文件删除问题
程序员文章站
2022-03-13 22:28:31
最近接触到一个功能,要删除SDCard的文件。结果失败了。下面是正确的方法:1. 向用户申请权限。调用下面的代码,会弹出一个文件预览Activity, 选择SDCard的文件目录。所以在UI上一定要先提示用户选择SDCard根目录。final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);startActivityForResult(intent, SDCARD_PERMISSION_REQUEST);2. 保存...
最近接触到一个功能,要删除SDCard的文件。结果失败了。
下面是正确的方法:
1. 向用户申请权限。调用下面的代码,会弹出一个文件预览Activity, 选择SDCard的文件目录。所以在UI上一定要先提示用户选择SDCard根目录。
final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, SDCARD_PERMISSION_REQUEST);
private void checkSDCardPermission() {
if (!DeviceStorageUtil.hasSDCard()) {
return;
}
CustomDialog dialog = new CustomDialog.Builder()
.setContext(this)
.setTitle(getString(R.string.cleanup_clean_sdcard_garbage))
.setMessage(getString(R.string.cleanup_clean_sdcard_permission_hint))
.setPositive(getString(R.string.cleanup_select_sd_card), new CustomDialog.onContinueClickListener() {
@Override
public void onContinueClick() {
final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, SDCARD_PERMISSION_REQUEST);
}
})
.build();
dialog.show();
}
2. 保存SDCard目录对应的URI,并且打开权限。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SDCARD_PERMISSION_REQUEST && resultCode == RESULT_OK) {
Uri url = data.getData();
if (url != null) {
getContentResolver().takePersistableUriPermission(url, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
DeviceStorageUtil.setSDCardPermissionUri(url);
}
}
}
3. 删除文件。
SDCARD_PERMISSION_URI就是上面一步取得的URI, SDCARD_UUID 就是SDCARD的识别码,类似于:“123-456:”
public static boolean deleteSDCardFile(File file) {
if (file != null) {
try {
Uri uri = DocumentsContract.buildDocumentUriUsingTree(SDCARD_PERMISSION_URI, SDCARD_UUID + file.getPath().replace(getSDCardRoot(), ""));
return DocumentsContract.deleteDocument(BaseApplication.getInstance().getApplicationContext().getContentResolver(), uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static String getSDCardRoot() {
if (!TextUtils.isEmpty(SDCARD_ROOT_FOLDER))
return SDCARD_ROOT_FOLDER;
String[] paths = null;
try {
StorageManager sm = (StorageManager) BaseApplication.getInstance().getApplicationContext().getSystemService(Context.STORAGE_SERVICE);
paths = (String[]) sm.getClass().getMethod("getVolumePaths").invoke(sm);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (paths != null) {
String external = Environment.getExternalStorageDirectory().getAbsolutePath();
for (String path : paths) {
if (!TextUtils.equals(path, external)) {
SDCARD_ROOT_FOLDER = path;
return path;
}
}
}
SDCARD_ROOT_FOLDER = null;
return null;
}
本文地址:https://blog.csdn.net/zjuter/article/details/112611293