5

I read some example in internet/book about the App Widget, a normal example to update the widget is in onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) method of AppWidgetProvider like this:

final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
 int appWidgetId = appWidgetIds[i];
 RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.mywidget_layout);
 updateViews.setTextViewText(R.id.mytext, "updated text");

 appWidgetManager.updateAppWidget(appWidgetId, updateViews);    
}

It update each Widgets in a loop.

But now, I have to implement an App Widget, it is updated in BroadcastReceiver, onReceive(Context context, Intent intent) method since there are no int[] appWidgetIds passed in. So I implemented the code like this:

RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.mywidget_layout);
updateViews.setTextViewText(R.id.mytext, "updated text");

ComponentName myComponentName = new ComponentName(context, AndroidBatteryWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myComponentName, updateViews);

It didn't update widget one-by-one, but actually all widgets were updated at once. Even though it worked as I want, but I got confused as to why there is no need to update all widgets one-by-one as before.

What's the difference between two methods?

Can I send another broadcast from BroadcastReceiver.onReceive() to trigger AppWidgetProvider.onUpdate()? And how to?

Artem Mostyaev
  • 3,874
  • 10
  • 53
  • 60
chow
  • 769
  • 2
  • 8
  • 10

1 Answers1

0

It's the same thing. Update with ComponentName loops through all the ids like your first code block.

You can see it in the Android code here:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/com/android/server/AppWidgetService.java#AppWidgetService.updateAppWidgetProvider%28android.content.ComponentName%2Candroid.widget.RemoteViews%29

Ran
  • 4,117
  • 4
  • 44
  • 70