Android 13 中文件未删除?

2024-04-27

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();        
}

文件没有被删除。但 toast 显示为“文件已删除”。我在这个问题上被困了近 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" />

解决方案#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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 13 中文件未删除? 的相关文章

随机推荐