How to show image in android remote view using content URI?

481 Views Asked by At

I am having trouble trying to show an image in a remote view with a contentUri. I have outlined the steps I took below. I believe I have followed the procedure correctly but still get a "Can't load widget" message. What am I doing wrong? Is the image saved to the correct storage area? Is the contentUri constructed correctly? Please help.

Blockquote

  1. Save the image into my file directory. I can see the image successfully saved in data/data/com.mydomain/files/myImage.jpg when I check using Android Studio's Device File Explorer.
val file = File(applicationContext.filesDir, "myImage.jpg")
try {
    FileOutputStream(file).use { out ->
        myBitmap?.compress(Bitmap.CompressFormat.JPEG, 90, out)
    }
} catch (e: IOException) {
    e.printStackTrace()
}
  1. Create a FileProvider in manifest and provider_paths.xml in res.xml
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>
<paths>
    <files-path name="name" path="." />
</paths>
  1. Create a content Uri using getUriForFile. This returns a content uri of: content://com.mydomain.provider/name/myImage.jpg
val file = File(getAppInstance().filesDir, "myImage.jpg")
val contentUri = FileProvider.getUriForFile(
    getAppInstance(),
    BuildConfig.APPLICATION_ID + ".provider",
    file
)
  1. I pass the content Uri into Image() composable.
Image(
    modifier = GlanceModifier.size(28.dp),
    provider = ImageProvider(contentUri),
    contentDescription = "Image"
)
  1. Result on run:

enter image description here

0

There are 0 best solutions below