【问题标题】:Android: Passing AppWidgetId to a ServiceAndroid:将 AppWidgetId 传递给服务
【发布时间】:2011-04-07 05:26:44
【问题描述】:

我的 HomeScreen 上有一个小部件,我在该小部件上添加了对按钮的点击。我将小部件 id 从小部件传递给服务,但是当我在服务中读取 WidgetId 时,它始终为 3。

小部件:

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

    for (int appWidgetId : appWidgetIds) {
        RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);

        Intent intent = new Intent(context, WidgetService.class);


        // prints the correct appWidgetId
        System.out.println(appWidgetId);


        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        remoteView.setOnClickPendingIntent(R.id.Button01, pendingIntent);

        appWidgetManager.updateAppWidget(appWidgetId, remoteView);
    }

    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

服务如下所示:

public int onStartCommand(Intent intent, int flags, int startId){
    if (intent != null && intent.getExtras() != null) {

        int widgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);

        // 3 is always printend
        System.out.println(widgetId);

        // More stuff here

    }
    return super.onStartCommand(intent, flags, startId);
}

那我做错了什么?

【问题讨论】:

    标签: java android widget android-widget


    【解决方案1】:

    AFAIK,如果没有一些诡计,你试图做的事情是行不通的。

    每个Intent 只能有一个未完成的PendingIntent。因此,如果您创建两个等价的Intents(匹配非额外数据),然后尝试创建两个PendingIntents,最终您真的会得到一个PendingIntent。使用哪个Intent 取决于您提供给getService()(或getActivity()getBroadcast())的标志。在您的情况下,将始终使用第一个 Intent

    如果您只有一个出色的PendingIntent,但只是想更新它的附加功能,FLAG_UPDATE_CURRENT 可以工作。但是,你想要 N 个优秀的PendingIntents

    我知道在您的情况下实现该功能的唯一方法是在 Intent 中放置一个唯一的操作字符串。由于您正在指定组件 (WidgetService.class),因此操作字符串将不会用于路由。但是,给您多个 PendingIntent 对象就足够了。

    【讨论】:

      【解决方案2】:

      只是添加到上面的评论中,请参阅此示例以了解如何使您的意图独特: http://developer.android.com/resources/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetProvider.html 这似乎是一个非常愚蠢的设计和更糟糕的解决方法,但我想就是这样。我花了很长时间才找到上面的简单示例。请特别注意 intent.setData(Uri) 调用。我将这些行剪切并粘贴到我的 onUpdate() 方法中,它终于奏效了。

      【讨论】:

      • 很棒的发现。一段时间以来,我一直在尝试解决这个问题,并且一直像基线示例一样。哎呀。非常感谢!
      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2015-06-20
      相关资源
      最近更新 更多