Android Studio MediaStore, below SDK 29 save image in sd card fails

≯℡__Kan透↙ 提交于 2020-06-17 09:31:21

问题


I need to save image in sd_card's pictures directory below Android 10.I have implemented scoped storage & This code works in sdk 29 & above, because MediaStore.getExternalVolumeNames was added in sdk 29. Below sdk 29 how to get getContentUri of sd_card .

  val values = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, destinationFileName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + context.applicationContext.getString(R.string.app_name))
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }

        val storageVolume = if (AppPreferences(context).getSwitchExternalStorage()) MediaStore.getExternalVolumeNames(context).last() else MediaStore.getExternalVolumeNames(context).first()
        val bmp: Bitmap? = BitmapFactory.decodeFile(source)

        val collection = MediaStore.Images.Media.getContentUri(storageVolume)
        val imageUri = context.contentResolver.insert(collection, values)

        context.contentResolver.openOutputStream(imageUri!!).use { out ->
            bmp?.compress(Bitmap.CompressFormat.JPEG, 100, out)
        }

        values.clear()
        values.put(MediaStore.Images.Media.IS_PENDING, 0)
        context.contentResolver.update(imageUri, values, null, null)

Please help me to fix this issue

来源:https://stackoverflow.com/questions/61960036/android-studio-mediastore-below-sdk-29-save-image-in-sd-card-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!