Search code examples
androidkotlinandroid-intenturiandroid-contentresolver

How do you get uri data from content intent in Kotlin?


New to Android programming. I'm trying to have my app open when an attachment that has my custom extension of ".replaysecret" is opened from whatsapp, messenger, gmail etc. The file is a pcm audio file I renamed with my extension. My app is opening correctly and I can see the uri data and I found some code that gives me the file name but I can't figure out how to get the file path or load the file data some other way. Any suggestions on what I should be doing?

Here is my intent filter

        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.BROWSABLE"/>
            <category android:name="android.intent.category.DEFAULT"/>

            <data android:scheme="content"/>

            <data android:host="*"/>

            <!--  Required for Gmail and Samsung Email App  -->
            <data android:mimeType="application/octet-stream"/>

            <!--  Required for Outlook  -->
            <data android:mimeType="application/replaysecret"/>
        </intent-filter>

Here is my code for getting the file name from the uri

    var uri = intent.data

    if(uri != null){
        var fileName: String? = null
        var cursor = contentResolver.query(uri!!, null, null, null, null)
        if (cursor != null) {
            cursor.moveToFirst()
            fileName = cursor.getString(0)
            fileName = fileName.substring(fileName.lastIndexOf(":") + 1)
            cursor.close()
        }

       //Can't figure out how to get file path or load file data
    }

This is the uri string when opening the attachment if it matters: content://com.google.android.gm.sapi/[email protected]/message_attachment_external/%23thread-a%3Ar1178448143327120464/%23msg-a%3Ar8356029736797240583/0.1?account_type=com.google&mimeType=application&2Foctet-stream&rendition=1


Solution

  • blackapps comment got me to the solution

        var uri = intent.data
    
        if(uri != null){
            var inputStream = this.contentResolver.openInputStream(uri)
            var byteArray = inputStream!!.readBytes()
    
            //do stuff with byteArray
        }