Xyand
Xyand

Reputation: 4488

Why is AppWidgetProvider.onUpdate called for all widget instances when new one is added?

I noticed that whenever I add new instances of the same AppWidget to the home screen, the appropriate AppWidgetProvider's onUpdate method is being called with the ids of all the instances in appWidgetIds.

The reference clearly states:

EXTRA_APPWIDGET_IDS The appWidgetIds to update. This may be all of the AppWidgets created for this provider, or just a subset. The system tries to send updates for as few AppWidget instances as possible.

Is this behavior intentional?

Is there a way to force onUpdate to be called only with the appropriate ids?

Is there are way to differentiate the affected instances from the others?

Upvotes: 0

Views: 1829

Answers (1)

sromku
sromku

Reputation: 4683

There is two options to create widgets: First option is without using configuration activity and then all widgets behave similar and they all could be updated at once without differentiation. The second one is by using configuration activity. And there you can get the widget id that was just created from the invoked configuration activity by:

Intent intent = getIntent();
Bundle extras = intent.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

You can persist this widget id in the sqlite for example with other information on this widget that was defined while the configuration steps.

So for your questions:

Is this behavior intentional?

I think that the answer - 'Yes'. Because widgets that were created without configuration step should behave similar and onUpdate is called at intervals defined by the updatePeriodMillis attribute in the AppWidgetProviderInfo.

Is there a way to force onUpdate to be called only with the appropriate ids?

No. from doc I can learn that such option doesn't exist.

Is there are way to differentiate the affected instances from the others?

Yes, you can decide when and which exact widget will be updated. You can achieve this by using onRecieve in the widget provider class:

  • Use configuration activity and persist each widget id. Or set pending intent to onClick event in the widget and pass the widget id within this intent to activity and then persist it. The idea - save the widget id, just to be able later to differ between them.
  • From your application (activity,service, alarm manager..) send broadcast with widget id you want to update.
  • onRecieve will catch the broadcast, will fetch the widget id and then you can work with concrete widget in the widget provider class.

Upvotes: 1

Related Questions