【发布时间】:2011-10-26 09:56:46
【问题描述】:
我有一个应用小部件,它只包含一个图像视图。我重绘该图像并将其作为 png 存储在应用程序的私有内存中,然后我使用 uri (widget.setImageViewUri(R.id.widget_icon, uri)) 设置 RemoteViews 的图像,而不是自己发送位图,因为在非常罕见的情况下我得到的情况! Binder 交易失败!!!
问题是,随着图像随着时间的推移而变化,小部件的图像不会改变。我用根资源管理器检查了保存的 png,它已正确更新。但未显示正确的图像。每个小部件都显示从添加到主屏幕时开始的图像。如果我使用 setImageViewBitmap(...) 它可以正常工作,除了罕见的失败的活页夹事务。
我使用以下方法从服务更新小部件。它不适用于 android 2.3.7 和运行 2.2 的模拟器。可能是什么问题呢?它是否以某种方式缓存?
public void updateWidget(Context context) {
// redraws the widget's image
updateIcon();
OutputStream stream;
try {
stream = context.openFileOutput("icon.png", Context.MODE_WORLD_READABLE);
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
return;
}
m_Icon.compress(CompressFormat.PNG, 100, stream);
try {
stream.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
Intent intent = new Intent(context, MyDialog.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent clickIntent = PendingIntent.getActivity(context, 0, intent, 0);
File file = new File(context.getFilesDir().getAbsolutePath() + File.separator + "icon.png");
// Uri uri = Uri.fromFile(file);
// update all widgets on home screen
for (int wid : appWidgetIds) {
RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);
widget.setOnClickPendingIntent(R.id.widget_layout, clickIntent);
// === EDIT ===
// Uri.fromFile(file); does not work correctly on android 2.1, only 2.2 and up
// widget's image will disappear
// widget.setImageViewUri(R.id.widget_icon, uri);
widget.setImageViewUri(R.id.widget_icon, Uri.parse(file.getPath()));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, wid);
appWidgetManager.updateAppWidget(wid, widget);
}
}
编辑: 我还尝试了自定义 ContentProvider 并设置“content://...”uri,但结果相同。小部件显示从添加到主屏幕时开始的图像,并且不会随着时间的推移而更新。
logcat 没有显示任何错误。
【问题讨论】:
-
您的所有图标都使用相同的 URI(相同的文件名),这就是问题所在。 URI 在文件、资源中必须是唯一的……系统不会更新可绘制对象,而是使用第一个加载的对象及其预期行为。我认为最好使用 FileProvider,并提供多个文件。您可以删除过时的,并使用新的 URI 更新小部件。
-
@AnisBENNSIR 这个问题是五年前提出并解决的......
-
对不起,赏金处于开放状态...我的评论将对新用户有用,接受的答案不是最佳解决方案。
标签: android widget uri android-appwidget android-imageview