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);开发者_如何学Python
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?
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
精彩评论