【问题标题】:Is there any way to create Uri from bitmap but i don't want to see it in image gallery?有什么方法可以从位图创建 Uri 但我不想在图片库中看到它?
【发布时间】:2020-11-10 08:06:05
【问题描述】:

场景:我在聊天应用程序中使用 MessagingStyle 通知。对于图片消息,我使用 setData 函数来创建对话风格的图片通知。

public Message setData(String dataMimeType, Uri dataUri)

此方法需要 dataUri 但我有图像的 URL,所以我从图像 url 创建了一个位图,然后使用下面的函数从 batmap 创建一个 uri。

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;
    }
}

问题:现在的问题是,当用户打开图片库时,这些通知图片会显示,因为我使用了 mediastore 创建 URI。我不希望这些图片显示在图库中。

限制:如果我必须再次生成此通知,我也会保存该 URI。所以我不能立即删除那张图片以避免在图库中显示。

问题:有没有办法将图像私下保存在画廊无法访问的外部存储中。但是通知管理器可以访问吗?

有什么方法可以创建 Uri 表单 url 而无需下载它?我已经尝试过了,但它也不起作用

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());

另一种解决方法是在通知中显示图像,使用消息样式(如 WhatsApp 中的对话)

【问题讨论】:

    标签: android android-notifications


    【解决方案1】:

    直接从 url 下载图像到 getExternalFilesDir() 中的文件。不要使用中间位图。

    MediaStore 无法访问您的 getExternalFilesDir(),因此 Gallery 应用程序不知道您在那里的文件。

    用户仍然可以使用“文件”应用查看这些图像。

    然后使用 FileProvider 来提供您的文件。使用 FileProvider.getUriForFile() 构造一个 uri。

    【讨论】:

    • 我使用 getCacheDir() 来存储文件。然后创建 URI 表单文件提供程序而不是媒体存储并解决了问题
    【解决方案2】:

    store your bitmap 作为File 在某些特定于应用程序的目录(不是图库)中并生成URI from file path。请注意 Scoped Storage 并选择合适的位置来存储 Bitmaps - 查看 HERE,可能 getFilesDir()/getCacheDir() 方法将是最佳选择

    同样值得一试的可能是这一行:

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

    (可能需要encodedImageUrl = URLEncoder.encode(imageUrl, "utf-8")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2020-05-08
      • 2012-08-18
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多