[英]File is not getting deleted in Android 13 - Java?
String path = "/storage/emulated/0/Recordings/Call/Two.mp3";
File file = new File(path);
if(file.exists()) {
File file2 = new File(file.getAbsolutePath());
file2.delete();
Toast.makeText(this, "File deleted.", Toast.LENGTH_SHORT).show();
finish();
}else
{
Toast.makeText(this, "File not exists", Toast.LENGTH_SHORT).show();
}
文件沒有被刪除。 但是吐司顯示為文件已刪除。我在這個問題上被困了將近 2 天,我們將不勝感激任何幫助。 提前致謝。
我在清單中使用了以下權限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
對於 Android 11 或更高版本,您可以使用MediaStore Api刪除文件(沒有MANAGE_EXTERNAL_Storage
)
在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());
});
}
});
你刪除 function,
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());
}
使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.