Search code examples
androidkotlintexttext-filesshare

How to share .txt file in kotlin android


I have a problem with sharing .txt file in android (Kotlin). Sharing simple text isn´t problem. But I need share this file via Bluetooth, Gmail etc. Everytime G-mail returns: "Couldn´t attach file".

my function for sharing:

  fun shareFile(file:File){
    val sharingIntent = Intent(Intent.ACTION_SEND)
    sharingIntent.setType("text/*")
     sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.absolutePath))
    startActivity(Intent.createChooser(sharingIntent, "share file with:"))
}

I have read all threads in this site but without any effect :-/


Solution

  • Finally I have a solution of my problem, I´m posting it here for anybody with the same problem:

    if (file.exists()) {
            val uri = FileProvider.getUriForFile(
                this,
                BuildConfig.APPLICATION_ID + ".provider",
                file
            )
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }