Android Q中不推荐使用getExternalStoragePublicDirectory [英] getExternalStoragePublicDirectory deprecated in Android Q

查看:290
本文介绍了Android Q中不推荐使用getExternalStoragePublicDirectory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已弃用 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:

  1. Context#getExternalFilesDir(String)
  2. MediaStore
  3. Intent#ACTION_OPEN_DOCUMENT
  1. Context#getExternalFilesDir(String)
  2. MediaStore
  3. 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.

推荐答案

基于文档,将DCIM/...用于

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆