Search code examples
androidfile-sharingstorage-access-framework

Sharing DocumentFile using FileProvider


if I want to share sourceFile of type File, I use FileProvider with authorities. Snippet:

val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(
    Intent.EXTRA_STREAM, FileProvider.getUriForFile(
        context,
        context.applicationContext.packageName + ".provider",
        sourceFile
    )
)
intent.type = "audio/ogg"
startActivity(context, Intent.createChooser(intent, context.getString(R.string.share_audio)), null)

What is a proper way to do that if sourceFile is a DocumentFile instead of File?

I couldn't fnd any sort of replacement for getUriForFile that works with DocumentFile. At the moment I just copy file to cache and then share it from there, but I guess there should be a better way.


Solution

  • What is a proper way to do that if sourceFile is a DocumentFile instead of File?

    You do not need FileProvider in that scenario. Instead, call getUri() on the DocumentFile, and use that Uri in your Intent.