【问题标题】:How do I cancel Pending Intents in a Android Widget?如何取消 Android 小部件中的待处理 Intent?
【发布时间】:2012-02-25 08:53:25
【问题描述】:

我有一些奇怪的行为,我只能假设是因为我正在使用 Pending Intent。

场景

我有一个有 4 个按钮的小部件 (4x1)。在小部件的 onUpdate 中,我为每个按钮添加了一个待处理的意图。我的意图触发一个带有捆绑参数的服务,并根据这个参数启动一些东西。我这样附加意图:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

Bundle b = new Bundle();
b.putString("myVariable", someVariable);

Intent intent = new Intent(context, AppStarterService.class);
intent.putExtras(b);

PendingIntent pendingIntent = PendingIntent.getService(context, buttopnPosition, intent, 0);
views.setOnClickPendingIntent(R.id.btnOne, pendingIntent);

问题

代码运行良好,直到用户决定更新按钮的内容。然后,一个新的 Pending Intent 就完成了。所以,当我再次按下按钮时,有时它仍然执行旧意图而不是新意图。我不知道如何更好地解释这一点。假设我的第一个意图参数是“TestOne”,在我更新后,新意图具有参数“TestX”。当用户单击按钮时,在我的服务中,我的意图附加功能仍然是“TestOne”而不是“TestX”。所以,我的猜测是,当小部件按钮内容发生变化时,我需要取消先前的意图。 这是问题吗?难道我做错了什么 ?如何取消旧意图,我需要重新创建它然后取消它?

感谢您的宝贵时间。

【问题讨论】:

  • 您在 views.setOnClickPendingIntent(R.id.btnOne, pendingIntent); 之前尝试过 pendingIntent.cancel(); 吗?

标签: android android-intent widget android-pendingintent


【解决方案1】:

即使使用 FLAG_UPDATE_CURRENT,您仍然遇到此问题,请尝试每次定义不同的 requestCode,如下所示:

private static int request = 0;
...
PendingIntent pendingIntent = PendingIntent.getService(context, request++, intent, 0);

所以每次创建一个新的 PendingIntent 时,都会使用一个新的 requestCode,至少在类生命周期中是这样。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我想你想将标志 http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_UPDATE_CURRENT 设置为 PendingIntent.getService 的最后一个参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多