android - 如何在 Android 中使用内容解析器插入文件?

标签 android android-contentresolver android-10.0 android-storage

我正在尝试将音频文件插入 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指定支持的集合之一( AlarmsMusicNotificationsPodcastsRingtones ),然后指定您想要的任何路径。
但请注意,RELATIVE_PATH本身对 Android 10 来说是新的。对于 Android 9 和更旧的设备,我建议直接写入文件系统。

关于android - 如何在 Android 中使用内容解析器插入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715250/

相关文章:

android - 电子邮件 ContentResolver 的问题

android - 如何在 Android 10 中获得唯一的设备 ID?

android - 在 Android 10 设备中,生物识别提示失败,并且锁屏顶部始终显示“错误已取消”

android - Flutter doctor --> Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)

android - 我想获取 WhatsApp 个人资料图片,但只获取姓名和联系电话?

android - 使用 ContentProvider 插入到多个表

安卓 Q : background activity starts

android - 在 SurfaceView 中处理事件

Android 浏览器 PhoneGap 没有 Caret(光标)在表单内

android - Android 网络库 : OkHTTP, Retrofit 和 Volley 的比较