Android Q中不推荐使用getExternalStoragePublicDirectory [英] getExternalStoragePublicDirectory deprecated in Android Q
问题描述
已弃用 getExternalStoragePublicDirectory 在Android Q
中,建议使用其他方式.那么如何指定要将相机应用程序生成的照片存储到DCIM
文件夹或DCIM
中的自定义子文件夹中?
As getExternalStoragePublicDirectory has been deprecated in Android Q
, and the recommendation is to use other means. then how can we specify that we want to store the generated photos from a camera app into the DCIM
folder, or a custom sub-folder within the DCIM
?
文档指出,接下来的3个选项是新的首选选项:
The documentation states that the next 3 options are the new preferred alternatives:
- Context#getExternalFilesDir(String)
- MediaStore
- Intent#ACTION_OPEN_DOCUMENT
选项1不存在,因为这意味着如果卸载该应用程序,照片将被删除.
Option 1 is out of the questions as it would mean that the photos get deleted if the app gets uninstalled.
选项3也不是选择,因为它将要求用户通过SAF文件浏览器选择位置.
Option 3 is also not a choice, as it would require the user to pick the location through the SAF file explorer.
我们剩下选项2,即MediaStore;但是没有文档说明如何用它代替Android Q中的getExternalStoragePublicDirectory.
We are left with option 2, the MediaStore; but there is no documentation on how to use it as a replacement for getExternalStoragePublicDirectory in Android Q.
推荐答案
Based on the docs, use DCIM/...
for the RELATIVE_PATH
, where ...
is whatever your custom subdirectory would be. So, you would wind up with something like this:
val resolver = context.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "CuteKitten001")
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/PerracoLabs")
}
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
resolver.openOutputStream(uri).use {
// TODO something with the stream
}
请注意,由于RELATIVE_PATH
是API级别29的新增功能,因此您需要在较新的设备上使用此方法,而在较旧的设备上使用getExternalStoragePublicDirectory()
.
Note that since RELATIVE_PATH
is new to API Level 29, you would need to use this approach on newer devices and use getExternalStoragePublicDirectory()
on older ones.
这篇关于Android Q中不推荐使用getExternalStoragePublicDirectory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!