Problem with image sharing intent in Kotlin

here I'm sharing the image intent. The image is in a drawable folder. Giving this excpetion. android.os.FileUriExposedException:

file:///storage/emulated/0/Android/data/com.example.arkkhano.myapplication/cache/myImage.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed(Uri.java:2356)

The code:

sharing_img.setOnClickListener {
    val myDrawable = tv_view_home2e.drawable
    val bitmap = (myDrawable as BitmapDrawable).bitmap
    val file = File(externalCacheDir,"myImage.png")
    val fOut = FileOutputStream(file)
    bitmap.compress(Bitmap.CompressFormat.PNG,90,fOut)
    fOut.flush()
    fOut.close()
    file.setReadable(true,false)
    val intent = Intent(Intent.ACTION_SEND)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file))
    intent.type = "image/png"
    intent.putExtra(Intent.EXTRA_SUBJECT,"Subject here")
    startActivity(Intent.createChooser(intent,"Share to "))
}

1 answer