主目录不允许音频内容://media/external/file;允许的目录是[Download, Documents]



我需要从服务器下载一个音频文件,它的工作仍然是29,我改变了30以上的代码我面临这个问题。我在这里查了一下,但没有找到答案。

这是我的代码片段

File destination = new File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator,  urltoDownload.getName());
final String  relativeLocation = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + urltoDownload.getName();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.TITLE, urltoDownload.getName());
values.put(MediaStore.Audio.Media.DISPLAY_NAME, urltoDownload.getName());
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
values.put(MediaStore.Audio.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Audio.Media.RELATIVE_PATH, "Audio/" + relativeLocation); 
Uri uri = getApplicationContext().getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);
ParcelFileDescriptor descriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri,"w"); //"w" specify's write mode
FileDescriptor fileDescriptor = descriptor.getFileDescriptor();
InputStream dataInputStream = getApplicationContext().openFileInput(destination.getPath());
OutputStream output = new FileOutputStream(fileDescriptor);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = dataInputStream.read(buf)) > 0)
{
output.write(buf, 0, bytesRead);
}
dataInputStream.close();
output.close();

适应. relative_path或者不使用MediaStore.Files.getContentUri("external")。不要拿走。files。一个。有更合适的。

最新更新