解决方案#1
对于 Android 11 或更高版本,您可以使用以下命令删除文件媒体商店 API https://developer.android.com/reference/android/provider/MediaStore#createDeleteRequest(android.content.ContentResolver,%20java.util.Collection%3Candroid.net.Uri%3E)(没有MANAGE_EXTERNAL_Storage
)
In onCreate()
String path = "/storage/emulated/0/Recordings/Call/Two.mp3";
private ActivityResultLauncher<Intent> deleteResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{path}, null, (path, uri) -> {
Log.d("onScanCompleted", uri.getPath());
});
}
});
你删除功能,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Uri fileUri = Uri.fromFile(new File(path));
ArrayList<Uri> arrayList = new ArrayList<>();
arrayList.add(fileUri);
PendingIntent pendingIntent = MediaStore.createDeleteRequest(getContentResolver(), arrayList);
deleteResultLauncher.launch(new IntentSenderRequest.Builder(pendingIntent).build().getFillInIntent());
}
解决方案2
With MANAGE_EXTERNAL_Storage
,只需添加MediaScannerConnection
String path = "/storage/emulated/0/Recordings/Call/Two.mp3";
File file = new File(path);
if (file.exists()) {
File file2 = new File(file.toString());
file2.delete();
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{path}, null, (path, uri) -> {
Log.d("onScanCompleted", uri.getPath());
});
Toast.makeText(this, "File deleted.", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(this, "File not exists", Toast.LENGTH_SHORT).show();
}