![](/img/trans.png)
[英]Exoplayer set mediaSource using ContentResolver#openFileDescriptor(Uri, String) , instead of Uri.parse(MediaStore.Audio.Media.DATA)
[英]Delete file using uri extracted from MediaStore.Audio.Media.DATA
在将此问题标记为重复之前,我想说我曾访问过许多类似的问题,但没有一个解决了我的问题。因此,我已经使用MediaStore从内部存储中提取了所有音频文件,并将其Uri以字符串形式存储,但是稍后我尝试时要使用file.delete使用该Uri删除音频,前者返回false。 以下是提取歌曲uri及其正常工作的代码:
Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection=MediaStore.Audio.Media.IS_MUSIC+"!=0";
Cursor c=getContentResolver().query(uri,null,selection,null,null);
if(c!=null)
{
c.moveToFirst();
do {
String audioName=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String album=c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String url=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
String size=c.getString(c.getColumnIndex(MediaStore.Audio.Media.SIZE));
audioInfoArrayList.add(new AudioInfo(url,audioName,artist,album));
}while (c.moveToNext());
c.close();
在这里,我已将所有与音频有关的信息存储在自定义类型的arrayList中,该信息还以字符串形式存储了上面提取的uri,可以使用getUrl()方法进行提取。 以下是我如何尝试删除代码的代码:
Uri uri= Uri.parse(audioInfo.get(position).getUrl()); //its actually returning the url stored above in string form
deleteFile(uri.getPath());
Log.i("logText","uri.getPath() : "+uri.getPath());
Log.i("logText","audioInfo.get(position).getUrl() : "+audioInfo.get(position).getUrl());
deleteFile函数:
public void deleteFile(String filePath){
if(filePath.startsWith("content://")){
ContentResolver contentResolver = context.getContentResolver();
contentResolver.delete(Uri.parse(filePath), null, null);
}else {
File file = new File(filePath);
if(file.exists()) {
if (file.delete()) {
Log.e("logText", "File deleted."); //condition 0
}else {
Log.e("logText", "Failed to delete file!"); //condition 1
}
}else {
Log.e("logText", "File not exist!"); //condition 2
}
}
}
最后是我的logcat,用于示例音频文件:
01-11 13:52:34.257 19982-19982/com.example.hp.myplayer E/logText: Failed to delete file! 01-11 13:52:34.257 19982-19982/com.example.hp.myplayer I/logText: uri.getPath() : /storage/emulated/0/bluetooth/Copy Copy Fireflies-Owl_City[www.Mp3MaD.Com].mp3 01-11 13:52:34.257 19982-19982/com.example.hp.myplayer I/logText: audioInfo.get(position).getUrl() : /storage/emulated/0/bluetooth/Copy Copy Fireflies-Owl_City[www.Mp3MaD.Com].mp3
注意:在调用deleteFile()时,条件1不会执行2或0,这对我来说意味着文件是使用该uri在存储中定位的,但无法删除,并且file.delete()返回false。
对于Android 6及更高版本,仅在清单中请求读取和写入外部存储许可是不够的。
您应该添加代码以要求您的应用程序用户确认请求的权限。
Google的运行时权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.