Home > other >  How to get image uri from drawable folder in android 12 or higher?
How to get image uri from drawable folder in android 12 or higher?

Time:01-14

I have a share intent in my android app which works well on android 11 and below but in android 12 it crashes becuase I'm using insertImage() [a deprecated method] to get the image uri . My code is as follows:

val path = BitmapFactory.decodeResource(resources,R.drawable.share)
//the below line has the insertImage() which is deprecated.
           val path1 = MediaStore.Images.Media.insertImage(contentResolver,path,"title",null)
           val uri = Uri.parse(path1)
           val shareIntent: Intent = Intent().apply {
           action = Intent.ACTION_SEND
           putExtra(Intent.EXTRA_TEXT, "hi")
           putExtra(Intent.EXTRA_STREAM,uri)
           flags = Intent.FLAG_ACTIVITY_NEW_TASK
           type = "image/*"
                                }
                                startActivity(Intent.createChooser(shareIntent, "null"))

I have tried almost all solutions on stackoverflow, none of them resolves my issue as they are all either outdated or just another explanations.

Any Help Regarding this issue Is welcomed!

CodePudding user response:

Try this

val imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE   "://"   
    packageName   "/drawable"   '/'   
    resources.getResourceEntryName(R.drawable.share))
val shareIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, "hi")
    putExtra(Intent.EXTRA_STREAM,uri)
    flags = Intent.FLAG_ACTIVITY_NEW_TASK
    type = "image/*"
}
startActivity(Intent.createChooser(shareIntent, "null"))

CodePudding user response:

Use FileProvider to share your path 'path1'.

  • Related