AppWidgetManager.getAppWidgetIds in activity returns an empty list

Ran picture Ran · Nov 28, 2013 · Viewed 8.4k times · Source

I have an appwidget that I'm trying to update from an activity.

To do that, I need the appwidget id.

I've used AppWidgetManager.getAppWidgetIds but it always returns an empty list.

I also used AppWidgetManager.getInstalledProviders to make sure that my ComponentName is correct, but still I get an empty list.

I've seen all the other questions about this, but I couldn't find something that worked for me.

Is there another way to solve this? or another way to update the widget?

My code:

ComponentName name = new ComponentName(packageName, boardcastReceiverClass);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
int[] ids = appWidgetManager.getAppWidgetIds(name);
if (ids != null && ids.length > 0) {
   getApplicationContext().sendBroadcast(getUpdateIntent(ids[0]));
}

Thanks.

UPDATE: I should mention that my AppWidgetProvider is in a library project. According to the ComponentName I get with getInstalledProviders, I used the package name of my app and the class name with the package name of the library.

Answer

sigrlami picture sigrlami · Dec 10, 2013

You can access your widget without knowing id

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

This let you access the widget without having to know the 'appWidgetID'. Then in activity:

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