将setData添加到Intent会在Android上更新小部件

时间:2013-09-02 17:21:53

标签: android-intent uri android-pendingintent appwidgetprovider

我有两个小部件和一个配置活动。我有更新小部件的问题。其中一个AppWidgetProvider类看起来像:

public class HolidaysWidgetProvider extends AppWidgetProvider {

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

    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int i=0; i<N; i++) {
        int appWidgetId = appWidgetIds[i];           
        HolidaysBlackWidgetProvider.updateAppWidget(context, appWidgetId);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.holidays_appwidget);
        views.setTextViewText(R.id.yearTV, Integer.toString(y));
        views.setTextViewText(R.id.monthTV, Integer.toString(m));
        appWidgetManager.updateAppWidget(appWidgetId, views);
        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }
}

我的小部件没有更新。但是在我添加以下代码之后 我的小部件开始更新:

    Intent configIntent = new Intent(context, HolidaysWidgetProvider .class);
    configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    configIntent.setData(Uri.withAppendedPath(Uri.parse("abc" + "://widget/id/"), String.valueOf(appWidgetId)));
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, configIntent, 0);
    views.setOnClickPendingIntent(R.id.widget, pendingIntent);

为什么添加此代码会使我的小部件有效?

1 个答案:

答案 0 :(得分:2)

根据getBroadcast PendingIntent中的代码而不添加setData是equals。因此,将pendingIntent设置为remoteView可能会导致错误的appWidgetId。设置数据只是一个黑客