Search code examples
androidandroid-fileandroid-fileprovider

Retrieving actual File instead of URI original location


Based on the docs used for configuring your app as a platform for sharing media files, how do I store an actual File as opposed to its orginal URI location using a FileProvider even though I've already been provided a URI from the Intent? For instance, if I wanted a URI string of "content://com.android.sample.fileprovider/my_images/JPEG_20180315_162048_-1397281749.jpg". Because as of now, I get "content://media/external/images/media/142607" with the following code:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media)


        val intent = intent
        val action = intent.action
        val type = intent.type

        type?.let {
            when (action) {
                Intent.ACTION_SEND -> {
                    if (it == getString(R.string.mime_type_text)) {
                        handleSendText(intent)
                    } else if (it.startsWith(getString(R.string.mime_type_image_any))) {
                        handleSendImage(intent)
                    }
                }
        }
}

private fun handleSendImage(intent: Intent?) {
        val imageUri = intent?.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
        imageUri?.let {

            // Logs "content://media/external/images/media/142607"
            Log.d("tag", it.toString())

            // Logs "/external/images/media/142607"
            Log.d("tag", File(it.path).toString())
        }       
}

Solution

  • how do I store an actual File as opposed to its orginal URI location

    Step #1: Call getContentResolver() on your Activity, to get a ContentResolver

    Step #2: Call openInputStream() on the ContentResolver, to get an InputStream on the content identified by the Uri

    Step #3: Copy the bytes from the InputStream to something (e.g., a FileOutputStream on a file that you control)

    Step #4: Once you have all that working, move it to a background thread, so that your I/O is not tying up the main application thread

    For instance, if I wanted a URI string of "content://com.android.sample.fileprovider/my_images/JPEG_20180315_162048_-1397281749.jpg"

    First, there is no requirement for every developer of every Android app to use FileProvider for sending you streams via ACTION_SEND.

    Second, it is quite likely that you do not have filesystem access to the file anyway.