Programmatically Update Widget from Activity/Service/Receiver

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);

Update Android Widget From Activity

I finally found the answer I was looking for, it was in an overload of the updateAppWidget function.

   appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);

This let me access the widget without having to know the appWidgetID. My final code in my activity is then:

        // Create an Intent to launch ExampleActivity
Intent intent = new Intent(this, Settings.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);
finish();

I have to do all the same setup stuff I had to do in the onUpdate method of the Widget, but now every time I exit my activity the Widget is displaying the correct state.

updating Textview of a widget when a service that runs a music player actually started playing

Sure, You can do that.

The widgetProvider is a broadcast receiver itself. So inorder to communicate with a widget, you just need to send a broadcast.

Intent intent = new Intent(this,YourWidgetProvider.class);
intent.putExtra("SONG","Your Song");
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 = {widgetId};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);

In onReceive Method of widgetprovider, You can extract the info required from the intent

Reference : Programmatically update widget from activity/service/receiver

Update AppWidget from an Activity

I had to use the package name of the app in component name and the full classname in the library in the class.



Related Topics



Leave a reply



Submit