首页 > 解决方案 > 远程视图服务意图上的 setData

问题描述

有什么用

serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));

Intent在AppWidgetProvider 类中的以下内容(参见下面的代码)

根据 CommonsWare 的书,原因是:

虽然您的应用程序可以访问您的 RemoteViewsService 类对象,但应用程序小部件主机不会,因此我们需要一些可以跨进程边界工作的东西。您可以选择将自己的添加到 RemoteViewsService 并使用基于此的 Intent,但这会使您的服务比您想要的更公开可见。

资料来源:忙碌的程序员 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);
    }

标签: androidwidgetbroadcastreceiverandroid-widgetcommonsware

解决方案


我想到了。如果不使用setData,系统将无法区分不同的服务意图,导致它对onGetViewFactory多个小部件只调用一次,并向所有小部件发送相同的意图。例如,如果您将应用小部件 id 发送给您的RemoteViewsService和从他们发送给您的,RemoteViewsFactory并将其显示在每个项目中,如果您不使用setData.


推荐阅读