到目前为止,我一直在使用remoteViews.setImageViewBitmap()
直接将位图加载到我的RemoteViews
中。总体上运作良好。
但是有几个用户遇到了问题,我认为可能是由于加载非常大的位图时出现的问题。我已经将位图缓存到本地存储器中,所以我的想法是改用建议中的setImageViewUri()
。
但我无法使其正常工作... 我只得到一个空白小部件。下面的代码片段说明了我的操作(省略了一些上下文但希望保留足够的信息)...
// 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
...
清单:
<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/file_paths.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中没有错误。
path="."
,并且在File
构造函数中也删除"."
。这两个都是不必要的,而且可能会干扰FileProvider
。我还建议你始终使用getFilesDir()
,替换openFileOutput()
。但是,我怀疑你的主要问题在于ContentProvider
权限——我已经编辑了我的答案。 - CommonsWaresetImageViewUri()
进行直接加载,以快速测试我的假设。 - drmrbrewerRemoteViews
从您的进程传递到操作系统进程,然后再传递到主屏幕进程。 “可能会发生这种情况...组合大小成为问题吗?”--据我所知不会,但我不能完全排除这种可能性。“我希望尝试使用setImageViewUri()进行直接加载,以快速测试我的假设。”--然后将文件暂时放在外部存储上,看看会发生什么。 - CommonsWare