Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :-/

like image 527
Vašek Doškář Avatar asked Dec 17 '25 21:12

Vašek Doškář


1 Answers

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)
    }
like image 108
Vašek Doškář Avatar answered Dec 19 '25 13:12

Vašek Doškář



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!