Programmatically update widget from activity/service/receiver Programmatically update widget from activity/service/receiver android android

Programmatically update widget from activity/service/receiver


If you are using an AppWidgetProvider, you can update it this way:

Intent intent = new Intent(this, MyAppWidgetProvider.class);intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);// Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,// since it seems the onUpdate() is only fired on that: int[] ids = AppWidgetManager.getInstance(getApplication())    .getAppWidgetI‌​ds(new ComponentName(getApplication(), MyAppWidgetProvider.class));intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);sendBroadcast(intent);


This helped when I searched on how to update a widget from a service/or action (but may be possible from every Context):

Context context = this;AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_2x1);ComponentName thisWidget = new ComponentName(context, MyWidget.class);remoteViews.setTextViewText(R.id.my_text_view, "myText" + System.currentTimeMillis());appWidgetManager.updateAppWidget(thisWidget, remoteViews);


So to update an widget from an activity, you can do it like this:

Intent intent = new Intent(this, DppWidget.class);intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), DppWidget.class));intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);sendBroadcast(intent);

Works for me :)