Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

后端 未结 19 2575
温柔的废话
温柔的废话 2020-11-22 02:44

Before KitKat (or before the new Gallery) the Intent.ACTION_GET_CONTENT returned a URI like this

content://media/external/images/media/39

19条回答
  •  温柔的废话
    2020-11-22 03:25

    If anyone's interested, I made a working Kotlin version for ACTION_GET_CONTENT:

    var path: String = uri.path // uri = any content Uri
    val databaseUri: Uri
    val selection: String?
    val selectionArgs: Array?
    if (path.contains("/document/image:")) { // files selected from "Documents"
        databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        selection = "_id=?"
        selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
    } else { // files selected from all other sources, especially on Samsung devices
        databaseUri = uri
        selection = null
        selectionArgs = null
    }
    try {
        val projection = arrayOf(MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.ORIENTATION,
            MediaStore.Images.Media.DATE_TAKEN) // some example data you can query
        val cursor = context.contentResolver.query(databaseUri,
            projection, selection, selectionArgs, null)
        if (cursor.moveToFirst()) {
            // do whatever you like with the data
        }
        cursor.close()
    } catch (e: Exception) {
        Log.e(TAG, e.message, e)
    }
    

提交回复
热议问题