我正在尝试将音频文件插入 Android 中的共享存储。我在 api 29(模拟器)上遇到错误。
错误:
java.lang.IllegalArgumentException: Primary directory (invalid) not allowed for content://media/external_primary/audio/media; allowed directories are [Alarms, Music, Notifications, Podcasts, Ringtones]
我的代码是:...
Uri collection = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
? MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
: MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
values = new ContentValues();
values.put(MediaStore.Audio.Media.DISPLAY_NAME, targetFileName);
values.put(MediaStore.Audio.Media.RELATIVE_PATH, targetFileDirPath);
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.IS_PENDING, 1);
resolver = getContentResolver();
uri = resolver.insert(collection, values); // error throws from here
outputStream = uri != null ? resolver.openOutputStream(uri) : null;
...
这个错误的原因是什么,我该如何解决这个问题?
最佳答案
显然,MediaStore.Audio.Media.getContentUri()
不返回可直接使用的 Uri
,至少在 Android 10+ 上。它指向“音频”的抽象位置,但您不能将内容直接写入该位置 Uri
.相反,您需要使用 RELATIVE_PATH
指定支持的集合之一( Alarms
、 Music
、 Notifications
、 Podcasts
、 Ringtones
),然后指定您想要的任何路径。
但请注意,RELATIVE_PATH
本身对 Android 10 来说是新的。对于 Android 9 和更旧的设备,我建议直接写入文件系统。
关于android - 如何在 Android 中使用内容解析器插入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715250/