多个待定意图实例

53

我创建了一个小部件,当点击它时会触发PendingIntent。问题是当屏幕上有多个小部件时,只有最新的一个会启动PendingIntent。

我已经了解了一些关于唯一请求代码的知识,但还没有想出来。

有什么办法可以让我拥有多个小部件并使每个PendingIntent都能正常工作吗?

这是我的代码片段:

Intent openApp = new Intent(context, RunningTally.class);
    openApp.putExtra("widgetId", appWidgetId);
    PendingIntent pendingAppIntent = 
        PendingIntent.getActivity(context, 0, openApp, PendingIntent.FLAG_CANCEL_CURRENT  );
    views.setOnClickPendingIntent(R.id.openFull, pendingAppIntent);
1个回答

116

我发完问题之后,恰好想到了答案。我将我的 appWidgetId 作为“唯一”的请求代码传递进去,就完成了!这是现在的代码片段:

Intent openApp = new Intent(context, RunningTally.class);
    openApp.putExtra("widgetId", appWidgetId);
    PendingIntent pendingAppIntent = 
        PendingIntent.getActivity(context, appWidgetId, openApp, 
                                  PendingIntent.FLAG_CANCEL_CURRENT);
    views.setOnClickPendingIntent(R.id.openFull, pendingAppIntent);

24
最糟糕的是文件说明写着:“requestCode是发送方的私有请求代码(目前未使用)”。我看到了这个说明,但我没有尝试使用它,因为我认为它不起作用! - thiagolr
5
值得注意的是 - 它不再标记为“当前未使用”http://developer.android.com/reference/android/app/PendingIntent.html#getBroadcast(android.content.Context,%20int,%20android.content.Intent,%20int)。 - Mr_and_Mrs_D
2
正如我所注意到的,这应该适用于任何类型的待定意图(包括通知的待定意图)。我认为最好创建一个管理所有类型的类,以避免对它们进行覆盖。 - android developer
3
关键在于请求代码必须是独一无二的。如果您传递了两个相同的代码,其中一个将无法正常工作。 - rickythefox
1
@android-developer 是的,使用不同请求代码的多个待定意图实例的概念也可以与AlarmManager完美配合。 - johnkarka
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接