I have an app that shares images from url. Last android update, I got message from instagram \"Unable to load image\" when I want to share an image in instagram feed.
Update: This issue was fixed in the version of Instagram released earlier this week. Workarounds no longer necessary.
None of the solutions mentioned above worked for me, as it seems that direct sharing via ContentProvider
or its derivative FileProvider
was broken by a change made within the Instagram app.
I did notice that sharing a MediaStore
content Uri still works, as other apps such as Google Photos that write to the MediaStore prior to sharing were still able to share images to feed.
You can insert an image File
to the MediaStore
as follows:
@SuppressLint("InlinedApi")
fun insertImageToMediaStore(file: File, relativePath: String): Uri? {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, file.name)
val mimeType = when (file.extension) {
"jpg", "jpeg" -> "jpeg"
"png" -> "png"
else -> return null
}
put(MediaStore.Images.Media.MIME_TYPE, "image/$mimeType")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
}
val collection = when (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
true -> MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
false -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val uri = contentResolver.insert(collection, values)
uri?.let {
contentResolver.openOutputStream(uri)?.use { outputStream ->
try {
outputStream.write(file.readBytes())
outputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
values.clear()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(uri, values, null, null)
}
} ?: throw RuntimeException("MediaStore failed for some reason")
return uri
}
Then with that Uri
that you're returned, share via Intent as follows:
val filePath = "/data/data/io.jammy.withintent/files/IMG-20200321_093350_2020-122758.jpg" // this is an example path from an app-internal image file
val context: Context? = this
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
insertImageToMediaStore(File(filePath), "Pictures/Your Subdirectory")?.let { uri ->
val clipData = ClipData.newRawUri("Image", uri)
intent.clipData = clipData
intent.putExtra(Intent.EXTRA_STREAM, uri)
val target = Intent.createChooser(intent, "Share Image")
target?.let { context?.startActivity(it) }
} ?: run {
Log.e(TAG, "Unsupported image file")
return
}
Whilst it's not ideal, as the image is then written to the MediaStore
, which may not be desired behaviour in many cases, it re-enables the ability to share in the medium term whilst Instagram fixes their whoopsie.