欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android10 uri转file

程序员文章站 2024-02-13 19:42:10
...
fun Uri.toFile(context: Context): File? = when (scheme) {
    ContentResolver.SCHEME_FILE -> toFile()
    ContentResolver.SCHEME_CONTENT -> {
        val cursor = context.contentResolver.query(this, null, null, null, null)
        val file = cursor?.let {
            if (it.moveToFirst()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    //保存到本地
                    val ois = context.contentResolver.openInputStream(this)
                    val displayName =
                        it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    ois?.let {
                        val file = File(
                            context.externalCacheDir!!.absolutePath,
                            "${Random.nextInt(0, 9999)}$displayName"
                        )
                        val fos = FileOutputStream(file)
                        android.os.FileUtils.copy(ois, fos)
                        fos.close()
                        it.close()
                        file
                    }
                } else
                //直接转换
                    File(it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA)))
            } else null

        }
        cursor?.close()
        file
    }
    else -> null
}