android uri获取文件名

从android11开始,文件只能通过uri操作,包括获取文件名

参考:https://developer.android.google.cn/training/data-storage/shared/documents-files#kotlin

    fun uriToFileName(uri:Uri,context: Context):String{
        return when(uri.scheme){
            ContentResolver.SCHEME_FILE -> uri.toFile().name
            ContentResolver.SCHEME_CONTENT->{
                val cursor = context.contentResolver.query(uri, null, null, null, null, null)
                cursor?.let {
                    it.moveToFirst()
                    val displayName = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    cursor.close()
                    displayName
                }?:"${System.currentTimeMillis()}.${MimeTypeMap.getSingleton().getExtensionFromMimeType(context.contentResolver.getType(uri))}}"

            }
            else -> "${System.currentTimeMillis()}.${MimeTypeMap.getSingleton().getExtensionFromMimeType(context.contentResolver.getType(uri))}}"
        }
    }

猜你喜欢

转载自blog.csdn.net/jingzz1/article/details/106002325
今日推荐