I have written just few widgets in android but one thing always made me curious. in the onUpdate() method we loop through all the widget ids and it says there can be multiple widget active so update them all . But why do we have to update other widget from one widget like this ?
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
Every widget has its own Broadcast reviever and each can run by itself. Why do we have to call update from another widget ?
Please take my question easily if this is a very simple logic.
Every widget has its own Broadcast reviever
No, it does not.
First, an AppWidgetProvider
class handles all app widgets provided by that provider. If the user creates several instances of that app widget (e.g., weather reports for several cities), all of them are updated by that single AppWidgetProvider
class.
Second, an individual instance of AppWidgetProvider
is used for a single onUpdate()
call. This is because AppWidgetProvider
is a subclass of BroadcastReceiver
, onUpdate()
is triggered by onReceive()
, and a manifest-registered BroadcastReceiver
gets a unique instance per onReceive()
call.