appWidgetIds只包含一个id

时间:2016-06-08 12:25:17

标签: android android-widget

我有appWidgetProvider来更新位于主屏幕上的每个小部件的视图,每个小部件都有一个触发更新视图的按钮,但显然无论我按哪个按钮,只按任何一个小部件,并且总是其中一个正在更新

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    for (int widgetId: appWidgetIds){
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);

        Intent update = new Intent(context, QuotesAppWidgetProvider.class);
        Bundle bundle = new Bundle();
        bundle.putIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{widgetId});
        update.putExtras(bundle);
        update.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, update, 0);

        views.setOnClickPendingIntent(R.id.widget_refresh, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, views);
    }
}

让我说我有id = 30的widget和id = 31的widget,我点击widget30上的刷新按钮,然后widget30正在更新,这是我们想要的但是当我点击widget31上的刷新按钮然后widget30正在更新,因为我不知道是什么原因。

2 个答案:

答案 0 :(得分:1)

它花了我一点但我终于明白了。所有小部件都有挂起的具有相同请求代码的小部件,因为它是广播的,所以它用一个覆盖所有小部件。这就是帮助我的路线:

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, widgetId, update, PendingIntent.FLAG_UPDATE_CURRENT);

答案 1 :(得分:0)

使用此代码并检查。

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    for (int widgetId: appWidgetIds){
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);

        Intent update = new Intent(context, getClass());
        update.setAction("actUpdateWidgets");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, update, 0);

        views.setOnClickPendingIntent(R.id.widget_refresh, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, views);
    }
}


@Override
    public void onReceive(Context context, Intent intent)
    {
        super.onReceive(context, intent);

        if (intent.getAction().equalsIgnoreCase("actUpdateWidgets"))
        {
          Intent i = new Intent(context, QuotesAppWidgetProvider.class);
          i.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
          int ids[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new                     ComponentName(context, QuotesAppWidgetProvider.class));
          i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
          context.sendBroadcast(i);
        }
    }