我正在尝试通过以下代码从手机内存中删除歌曲文件:
private void deleteSongs(){
String path = song.getPath();
File songFile = new File(path);
Log.d(TAG, "Song exists: " + songFile.exists());
Log.d(TAG, "Song is directory: " + songFile.isDirectory());
Log.d(TAG, "Song path: " + songFile.getPath());
Log.d(TAG, "Song name: " + songFile.getName());
if(songFile.delete())
Log.d(TAG, "Song deleted successfully by File.delete()");
else{
Log.d(TAG, "Can't delete file by File.delete()");
if(getActivity().deleteFile(songFile.getName()))
Log.d(TAG, "Song deleted successfully by Activity.deleteFile()");
else
Log.d(TAG, "Can't delete file by Activity.deleteFile()");
}
}
但是它不起作用。 Logcat说:
D/DeleteSongDialog: Song exists: true
D/DeleteSongDialog: Song is directory: false
D/DeleteSongDialog: Song path: /storage/emulated/0/Download/2 sekundowy film-20.m4a
D/DeleteSongDialog: Song name: 2 sekundowy film-20.m4a
D/DeleteSongDialog: Can't delete file by File.delete()
D/DeleteSongDialog: Can't delete file by Activity.deleteFile()
带有FileProvider的solution在Android> = 8.0上无效,但在Android 7.0上有效。也许有人知道我应该更改我的@CodeToLife代码还是什么?
谢谢。
答案 0 :(得分:2)
将getActivity().deleteFile(songFile.getName())
替换为songFile.delete()
。另外,请确保您具有WRITE_EXTERNAL_STORAGE
权限,包括在Android 6.0+上的运行时请求该权限。
答案 1 :(得分:0)
@CommonsWare帮助我找到了解决方案。我必须在以下位置更改此代码:
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.getId());
getActivity().getContentResolver().delete(uri, null, null);
希望它也会对您有帮助