我试图通过我的应用程序删除音乐文件,但无法实现。我检查过
boolean exists = temp.exists();
boolean isFile = temp.isFile();
如果是真的,是的。这些方法返回 true。 但是当我谈到删除方法时:
boolean deleted = temp.delete();
它返回 False 并且文件没有被删除。没有异常抛出,只是对我删除的变量的错误返回。
我也在使用这些权限:
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACTION_HEADSET_PLUG"/>
有人有解决方案的想法吗? (或者我可以使用的其他类(class)?)
编辑: 这是我的完整代码
File temp = new File(str_path);
boolean exists = temp.exists();
boolean isFile = temp.isFile();
if (exists)) {
boolean deleted = temp.delete();
if (deleted) {
Toast.makeText(context, "Successful deleted " + Title_Artist, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Not able to delete file " + Title_Artist, Toast.LENGTH_SHORT).show();
}
}
(我在调试时检查了对象是否有他的路径并且它有)
最佳答案
删除文件音乐你必须做两个任务:
删除存储中的文件。
public static boolean delete(File path) { boolean result = true; if (path.exists()) { if (path.isDirectory()) { for (File child : path.listFiles()) { result &= delete(child); } result &= path.delete(); // Delete empty directory. } if (path.isFile()) { result &= path.delete(); } if (!result) { Log.e("Delete", "Delete failed;"); } return result; } else { Log.e("Delete", "File does not exist."); return false; } }
从 MediaStore 中删除文件:
public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk >= android.os.Build.VERSION_CODES.HONEYCOMB) { String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { canonicalPath = file.getAbsolutePath(); } final Uri uri = MediaStore.Files.getContentUri("external"); final int result = contentResolver.delete(uri, MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath}); if (result == 0) { final String absolutePath = file.getAbsolutePath(); if (!absolutePath.equals(canonicalPath)) { contentResolver.delete(uri, MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath}); } } } }
您可以重置/重新扫描 MediaStore 而不是执行上面的一些代码。
注意:如果从SD卡和android 4.4+删除
Change for Android 4.4+ : Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.
关于android - 无法使用文件类删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34812076/