RemoteViewService 意图上的 setData

setData on RemoteViewService intents

有什么用
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));

在 AppWidgetProvider 中的以下 Intent class(参见下面的代码)

根据CommonsWare的书,原因是:

While your application has access to your RemoteViewsService Class object, the app widget host will not, and so we need something that will work across process boundaries. You could elect to add your own to the RemoteViewsService and use an Intent based on that, but that would make your service more publicly visible than you might want.

来源:Android 开发的忙碌编码员指南 https://commonsware.com/Android/

但是当我删除这一行时,没有任何改变。该小部件仍然有效。

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int appWidgetId : appWidgetIds) {

        [...]

        Intent serviceIntent = new Intent(context, WidgetService.class);
        serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));

        views.setRemoteAdapter(R.id.stack_view, serviceIntent);
        views.setEmptyView(R.id.stack_view, R.id.empty_view);

        [...]

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

我明白了。 如果不使用setData,系统无法区分不同的服务意图,这会导致它只为多个小部件调用一次onGetViewFactory,并向所有这些小部件发送相同的意图。 例如,如果您将应用程序小部件 ID 发送到您的 RemoteViewsService,然后从他们发送到您的 RemoteViewsFactory 并将其显示在每个项目中,如果您不这样做,它将为小部件的所有实例显示相同的 ID不要使用 setData.