1

Scenario: I am using MessagingStyle notification in a chat application. For image messages, I am using setData function to create image notification in conversation style.

public Message setData(String dataMimeType, Uri dataUri)

This method required dataUri but I have URL of image so I have created a bitmap from image url and then create a uri from batmap using function below.

public static Uri getImageUri(Context applicationContext, Bitmap photo) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), photo, "IMG_" + Calendar.getInstance().getTime(), null);
        if (path == null) {
            return null;
        }
        return Uri.parse(path);
    } catch (SecurityException ex) {
        ex.printStackTrace();
        return null;
    }
}

Problem: Now the problem is that when user open image gallery, these notifications images are showing because I used mediastore to create URI. I don’t want these image to show in gallery.

Limitation: I am also saving that URI in case If I have to generate this notification again. So I can’t delete that image immediately to avoid showing in gallery.

Question: Is there any way to save image privately in external storage where gallery don’t have access. But notification manager can access?

Is there any way to create Uri form url without downloading it? I have tried this but it also not working

url = new URL(messageNotification.getAttachmentImage());
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
imageUri=  Uri.parse(uri.toString());

Another workaround to show image in notification by using Messagings style like conversation as in WhatsApp

bilal
  • 2,187
  • 3
  • 22
  • 23

2 Answers2

1

store your bitmap as File in some app-specific directory (not gallery) and make URI from file path. be aware of Scoped Storage and pick proper place for storing Bitmaps - check out in HERE, probably getFilesDir()/getCacheDir() method will be the best option

also worth trying may be this line:

Uri uri =  Uri.parse(messageNotification.getAttachmentImage());

(encodedImageUrl = URLEncoder.encode(imageUrl, "utf-8") may be needed)

snachmsm
  • 17,866
  • 3
  • 32
  • 74
1

Download your image directly from url to a file in getExternalFilesDir(). Dont use an intermediate bitmap.

The MediaStore has no access to your getExternalFilesDir() so Gallery apps dont know about your files there.

The user can still use the Files app to see those images.

Then use a FileProvider to serve your files. Construct an uri with FileProvider.getUriForFile().

blackapps
  • 8,011
  • 2
  • 11
  • 25
  • I have used getCacheDir() to store file. Then created URI form file provider instead of media store and solved the problem – bilal Nov 11 '20 at 06:15