2016-06-08 105 views
0

我有appWidgetProvider更新位於主屏幕上的每個小部件的視圖,並且每個小部件都有一個觸發更新視圖的按鈕,但顯然不管哪個按鈕我按下哪個小部件而且總是其中一個是正在更新appWidgetIds只包含一個ID

@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和ID = 31小部件,我點擊widget30刷新按鈕,然後widget30它需要被更新,但是當我點擊上widget31刷新按鈕那麼widget30正在更新,我不知道是什麼原因。

回答

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); 
     } 
    } 
0

它花了我一下,但我終於明白了。所有的小部件都有具有相同請求代碼的候選人,並且由於它被廣播,所以它們全部用一個覆蓋。這是幫助我的線路:

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