1

我正在尝试支持范围存储并尝试统一处理媒体文件的实现:将媒体文件插入到 mediaStore 已成功完成但具有任意名称,例如:如果文件名是geeks.jpg它实际上将其创建为 ex599345665432.jpg

fun writeImage(inputStream: InputStream, fileName: String): Uri? {
    val collectionUri = if (atLeastQ()) {
        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
    } else {
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    }

    val imageDetails = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        put(MediaStore.Images.Media.TITLE, fileName)
        if (atLeastQ()) put(MediaStore.Images.Media.IS_PENDING, 1)
    }

    val imageContentUri = contentResolver.insert(imageCollection, imageDetails)
    imageContentUri?.let {
        contentResolver.openOutputStream(it)?.use { outputImageFile ->
            inputStream.writeFully(outputImageFile)
        }

    if(atLeastQ()) {
         imageDetails.clear()
         imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)
         contentResolver.update(imageContentUri, imageDetails, null, null)
      }
    }
    return imageContentUri
}

private fun atLeastQ() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
4

0 回答 0