You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 13文件无法删除求助:提示已删除但实际未删除

问题定位

你的代码里file.exists()返回了true,所以弹出了删除成功的提示,但delete()操作实际上失败了——你没判断这个方法的返回值,这是第一个需要修正的点。结合Android存储机制,核心问题集中在权限未正确获取和分区存储限制两方面。


解决方案

1. 先确认删除操作的真实结果

修改代码,直接判断delete()的返回值,同时去掉冗余的file2对象创建:

String path = "/storage/emulated/0/Recordings/Call/Two.mp3";
File file = new File(path);

if(file.exists()) {
    boolean isDeleted = file.delete();
    if(isDeleted) {
        Toast.makeText(this, "File deleted.", Toast.LENGTH_SHORT).show();
        // 通知媒体库更新,避免文件已删但仍显示的缓存问题
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        finish();   
    } else {
        Toast.makeText(this, "删除失败,请检查权限或文件状态", Toast.LENGTH_SHORT).show();  
    }
}else {
    Toast.makeText(this, "File not exists", Toast.LENGTH_SHORT).show();        
}

2. 确保权限真正被授予

  • Android 10(API 29)及以下:仅在Manifest声明WRITE_EXTERNAL_STORAGE没用,必须动态申请权限:

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
    }
    

    还要在onRequestPermissionsResult中确认用户是否授予权限。

  • Android 11(API 30)及以上:MANAGE_EXTERNAL_STORAGE是特殊权限,需要引导用户到系统设置手动开启:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        }
    }
    

    注意:该权限会触发Google Play审核,非必要建议改用应用专属目录或MediaStore API。

3. 适配分区存储(Android 10+)

Android 10默认启用分区存储,APP无法直接操作公共目录文件,可临时添加以下属性绕过限制(仅适用于Android 10/11):

<application
    ...
    android:requestLegacyExternalStorage="true">

长远来看,建议用MediaStore API删除公共媒体文件:

ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.DATA + "=?";
String[] selectionArgs = new String[]{path};
int deletedRows = resolver.delete(uri, selection, selectionArgs);
if(deletedRows > 0) {
    Toast.makeText(this, "文件删除成功", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
}

4. 排查其他可能性

  • 文件可能被其他进程占用(如正在播放、被其他APP打开),重启设备后再测试。
  • 打印路径确认是否正确:Log.d("File Path", file.getAbsolutePath()),排查文件名大小写或拼写错误。

内容的提问来源于stack exchange,提问作者Anandh Krishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:50:20