android - 无法从存储中删除文件
问题描述
我正在尝试从手机存储中删除一个文件,但它总是返回 false。我已经尝试了堆栈上给出的大多数方法,但没有任何效果。
final File file = new File(path);
if (path != null) {
AlertDialog alertDialog = new AlertDialog
.Builder(getContext()).setTitle("Delete")
.setMessage("Are you sure you want to delete this video?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean fileDeleted = file.delete();
Toast.makeText(getContext(), String.valueOf(fileDeleted), Toast.LENGTH_SHORT).show();
mAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
解决方案
这是我尝试了很多方法后使用的代码。
private static boolean delete(final Context context, final File file) {
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[] {
file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
if (file.exists()) {
contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}
推荐阅读
- php - Laravel nova 使资源只显示用户的数据
- python - 代码在本地运行良好,但部署到 heroku 时得到“错误:(-215:断言失败)!image.empty()”
- java - 在自定义存储库中使用 SpringBoot 和 JPA Criteria Query 查询时间戳
- javascript - 通过ajax发送2个数组
- python - 如何减少处理大数据框的时间
- javascript - 使用javascript和php的src切换
- shell - 在 shell 脚本中使用 sudo
- freemarker - Freemarker 和换行符空白
- javascript - 在这种情况下,如何将 Tensorflow.js 与 node.js 一起使用?
- r - 找到计算 R 中数百万个组合的最高可能 Pearson 相关性的最佳方法