问题
I have a couple of widgets which are basically quick links to functionality within my app,
These widgets are basically ListView/GridViews which are being backed by data that changes during the main App's execution.
Since the data is only changed during app execution the update frequency is set as so:
android:updatePeriodMillis="0"
and on the data changed I fire the following:
public void updateWidget(@SuppressWarnings("rawtypes") Class provider) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
int[] gridids = appWidgetManager.getAppWidgetIds(new ComponentName(this.getPackageName(), provider.getName()));
Intent intent = new Intent(this, provider);
intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,gridids);
sendBroadcast(intent);
}
I'm able to catch this in the onReceive() of the Provider and from their call the update mechanism:
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.e(this.getClass().getSimpleName(), "onReceive()");
int[] ids = intent.getExtras().getIntArray("appWidgetIds");
for(int id : ids) onUpdateWithService(context, id);
}
protected void onUpdateWithService(Context context, int widgetId) {
super.onUpdateWithService(context, widgetId);
RemoteViews views = new RemoteViews(context.getPackageName(), getResourceLayout(context, widgetId));
Intent intent = new Intent(context, GridViewWidgetServiceAdapter.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
views.setRemoteAdapter(R.id.listView, intent);
views.setPendingIntentTemplate(R.id.listView, PendingIntent.getActivity(context, -1, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(widgetId, views);
}
The problem I'm having is that although the code fires and updateAppWidget() is called, the UI of the widget doesn't change.
Am I missing a trick involved in Widget updates?
回答1:
This answer seems to fix the problem.
Not sure why it fixes the problem, but it does...
Adding the following line to the intent works fine
Intent intent = new Intent(context, GridViewWidgetServiceAdapter.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
intent.putExtra("Random", Math.random() * 1000); // Add a random integer to stop the Intent being ignored.
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
来源:https://stackoverflow.com/questions/18183415/widget-ui-not-updating-in-response-to-broadcast