gpt4 book ai didi

Android:将位图从本地存储加载到应用程序小部件(RemoteViews)

转载 作者:行者123 更新时间:2023-11-29 14:46:33 25 4
gpt4 key购买 nike

到目前为止,我一直使用 remoteViews.setImageViewBitmap() 直接将位图加载到我的 RemoteViews 中。总的来说它工作正常。

但是一些用户遇到了问题,我认为是在加载非常大的位图中时出现的问题。无论如何,我已经将位图缓存到本地存储,所以我的想法是改用 setImageViewUri(),正如其他地方所推荐的那样。

但我无法让它工作...我只是得到一个空白的小部件。以下 fragment 说明了我在做什么(省略了一些上下文,但希望留下足够的内容)...

// Bitmap bmp is fetched from elsewhere... and then...

FileOutputStream fos = context.openFileOutput("img.png", Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();

// ... later ...

// this works...
remoteViews.setImageViewBitmap(R.id.imageView, bmp);

// but this doesn't...
remoteViews.setImageViewUri(R.id.imageView, Uri.fromFile(new File(context.getFilesDir().getPath(), "img.png")));

编辑

尝试按照下面 CommonsWare 的建议使用 FileProvider...

list :

<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xyz.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>

xml/文件路径.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="cache" path="."/>
</paths>

代码:

File imagePath = new File(context.getFilesDir(), ".");
File newFile = new File(imagePath, "img.png"); // img.png created as above, in top level folder
remoteViews.setImageViewUri(R.id.imageView, FileProvider.getUriForFile(context, "com.xyz.fileprovider", newFile));

但我仍然像以前一样留下一个空白小部件,并且 logcat 中没有错误。

最佳答案

您的应用小部件正在主屏幕上呈现。主屏幕无法访问您应用的内部存储空间。

相反,尝试 using FileProvider使用 FileProvider 在您的 setImageViewUri() 调用中提供的 Uri 提供来自内部存储的文件。

更新:我忘记了 FileProvider 的权限限制。我不知道通过 RemoteViews 向主屏幕进程授予 Uri 权限的可靠方法。理想情况下,您只允许导出提供程序,但 FileProvider 不支持。

那么,您的选择是:

  1. 编写您自己的流式传输 ContentProvider,类似于 this one ,其中导出提供者,因此任何人都可以使用 Uri 值。

  2. 将文件放在外部存储上,而不是内部存储上,然后希望主屏幕具有 READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE 权限。

    <
  3. 确保您的图像始终相当小,以便您的 IPC 事务保持在 1MB 限制以下,并使用您原来的 setImageViewBitmap() 方法。

我很抱歉忘记了 FileProvider 不允许导出提供程序。

关于Android:将位图从本地存储加载到应用程序小部件(RemoteViews),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com