Search code examples
androidkotlinfileintentfilter

How do I get the file contents when an app is chosen to a open file? (Android Kotlin)


I have an Android app written in Kotlin. I want it to open files of a specific format (let's just say ".json" for now). When it is chosen from an app chooser by the user to open a certain file, what do I do next? How do I get that file into my code?


Solution

  • You should to declare a Intent filter.

    Add to your AndroidManifest.xml an intent filter to handle the specific file type.. you case a json type.

    <activity android:name=".YourActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="content" />
        <data android:mimeType="application/json" />
    </intent-filter>
    

    And in your Activity code you should to handle these file received, something like that:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_your)
    
        handleIncomingIntent(intent.data)
    } 
    
    private fun handleIncomingIntent(intent: Intent) {
        if (intent.action == Intent.ACTION_VIEW) {
            val uri: Uri? = intent.data
            uri?.let {
                val contents = content resolver.openInputStream(uri)?.bufferedReader()?.readText()
            }
        }
    }
    

    Since we are handling files through the content scheme and not directly accessing the file system, there is no need to request READ_EXTERNAL_STORAGE permissions. Content URIs handle file access securely, and your app will not need special permissions for this. Android Permissions

    Thanks @CommonsWare for the contributions.