I recently started developing widgets in java and I am not entirely sure about the general concept when it comes to using and managing multiple widgets. I am using an AppWidgetProvider to update the widget UI and to register click-listener. I would expect the onUpdate() Method to have either all appWidgetIds or the appWidgetIds of the widgets that need to be updated. However as of now, I will always get the id of the widget that I have least recently created, irregardless of which one is clicked. One time I received all widgetIds that have been created so far, but that changed after I placed another one. The same problem seems to be present with the code getIntArrayExtra();
In the end I want to have multiple widgets that display individual data and that are updated either themselves or all at once when I click on one of them. I have yet to find a way to bind individual data to a single widget and to get the widget itself (since it does not show up in the ids after placing another one).
It would be very helpful if you could add some explaining background information or point out some problems in the code below, thanks!
public class Slideshow extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Intent intent = new Intent(context, UpdateSlideshowService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
context.startService(intent);
}
public class UpdateSlideshowService extends Service {
@Override
public void onStart(Intent intent, int startId) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int widgetId : allWidgetIds) {
int number = (new Random().nextInt(100));
Intent clickIntent = new Intent(this.getApplicationContext(), Slideshow.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(),
R.layout.slideshow);
remoteViews.setTextViewText(R.id.update, "Random: " + number);
remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
stopSelf();
super.onStart(intent, startId);
}
I think most of the problem has been answered by this here: http://www.bogdanirimia.ro/android-widget-click-event-multiple-instances/269/comment-page-1