我创建了一个 Appwidget,它显示一个图像文件 (test.png),该文件通过 Uri 提供给它的 RemoteViews。
在 onUpdate 中,我运行一个更改文件内容的服务。我还为将调用 onUpdate 的图像设置了一个 onClickListener。
-如果我创建 AppWidget 的实例,它将显示 Uri 文件的最近更改的版本。
-如果我单击小部件,我的服务会对文件进行适当的更改(我可以使用文件资源管理器进行验证),但它不会更新 AppWidget 中显示的图像。
-(最重要的是)如果我删除 AppWidget 并创建一个新的 AppWidget,它会显示图像文件的当前/正确版本。
我知道我的服务可能需要很长时间才能在第一次通过时生效,但它应该在 onUpdate 的下一次 onClick/调用时显示最新的图像。
就目前而言,AppWidget 仅显示第一次调用 onUpdate 时存在的图像文件的版本。
问题:
刷新应用程序小部件的 RemoteView 内容的正确方法是什么,我在此处的方法中是否遗漏了某些内容?
谢谢你的时间!
Update:
我尝试从 AppWidgetProvider.onReceive() 调用 AppWidgetManager.notifyAppWidgetViewDataChanged() 方法,但在 onUpdate() 之后仍然没有更改为 RemoteViews 内容。
public class CCWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds)
{
// Get all ids
ComponentName thisWidget = new ComponentName(context,CCWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds)
{
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout04);
/*
* it's here that I run a service that changes the content of the file /test/test.png
*/
RelativeLayout RL_widget = new RelativeLayout(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
RL_widget = (RelativeLayout)inflater.inflate(R.layout.widget_main, null);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/test/test.png");
remoteViews.setImageViewUri(R.id.IV_widget_image,uri);
Intent intent = new Intent(context, CCWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
//PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.IV_widget_image, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}