Search code examples
androidandroid-intentandroid-resourcesandroid-sharing

Share a resource image with intents


I'm trying to share an image/jpg stored in the raw resource folder of my application, but the Intent seems not to find the image resource and sends nothing.

Here is my code for sending (in Kotlin):

val current = filePaths!![mViewPager!!.currentItem]
val uri = Uri.parse("android.resource://" + getPackageName() + "/" + current.resourceId)
val shareIntent : Intent = Intent()
shareIntent.setAction(Intent.ACTION_SEND)
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
shareIntent.setType("image/*")
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)))

I also tried to send the Uri this way:

val uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator + File.separator + getPackageName() + "/raw/" + filename)

but it doesn't work either. Can somebody help me?


Solution

  • After 3 days of headaches i finally solved... what i've done was just save the image resource and then serve it:

    val current = filePaths!![mViewPager!!.currentItem]
    
    val imagePath = File(Environment.getExternalStorageDirectory(), "_temp")
    
    if(!imagePath.exists())
       imagePath.mkdirs()
    
     val imageToShare = File(imagePath, "share.jpeg")
    
    if(imageToShare.exists())
        imageToShare.delete()
    
     imageToShare.createNewFile()
    
     val out = FileOutputStream(imageToShare)
     val imageToSave = utils.createBitmap(current.resourceId)
     imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out)
     out.flush()
     out.close()
    
     val uri = Uri.fromFile(imageToShare)
    
     val shareIntent : Intent = Intent()
     shareIntent.setAction(Intent.ACTION_SEND)
     shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
     shareIntent.setType("image/jpeg")
     startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)))
    

    :)