Search code examples
androidandroid-intentandroid-widgetandroid-pendingintentandroid-broadcast

How to broadcast intent to multiple WidgetProviders


I have 2 widgets, each having it's own WidgetProvider. This is the class hierarchy:

      AppWidgetProvider
             |
    CommonWidgetProvider
     |                |  
WidgetAProvider  WidgetBProvider

Both widgets have a button which updates the widget, but I would like to update all widgets (both WidgetA and WidgetB) no matter on which one you click.

I broadcast the update intent like this (in WidgetA):

don't worry about EXTRA_APPWIDGET_IDS containing only current widgets' id - I later retrieve all widgets' IDs in the Provider

// setup click on update icon
Intent intent = new Intent(data.context, WidgetAProvider.class); // how can I broadcast to both A AND B? Now it will broadcast only to A.
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {data.widgetId});

PendingIntent pendingIntent = PendingIntent.getBroadcast(data.context,
    data.widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.widgetUpdateContainer, pendingIntent);

How can I broadcast this update to both WidgetProviders?


Solution

  • Don't use the PendingIntent to directly send a broadcast because this way you always have to target explicitly one of the AppWidgetProviders.

    Instead, use the PendingIntent to start an IntentService to send a broadcast to every BroadcastReceiver which uses a certain IntentFilter. You can inhibit third party BroadcastReceivers from receiving your broadcast by using signature permissions (see for example this post)