我有一个前台服务通知,当点击它时应该开始一个 Activity 。此 Activity 在调用 finish() 之前非常短暂。
第一次点击通知时有效,第二次和之后出现错误:
Sending contentIntent failed: android.app.PendingIntent$CanceledException
在创建前台服务通知时的代码中,我将 randomActivity.class 更改为另一个不调用 finish 的 Activity 类,它在每次点击时都能完美运行。来自:
Intent notificationIntent = new Intent(this, RandomActivity.class);
到:
Intent notificationIntent = new Intent(this, HomeActivity.class);
工作正常...
我使用了来自 Android 开发者网站的标准通知代码,并使用 Notification builder 对其进行了测试。无论如何,我得到相同的结果。除非 Activity 调用 finish(),否则它会完美运行;
这是预期的行为、错误,还是我遗漏了什么?
在此先感谢您的帮助,希望能找到解决方案!
注:我用的通知码是完全标准的,所以没贴出来。 RandomActivity 调用 finish();在 onCreate 中,所以那里也没有什么异常。
最佳答案
在尝试了所有可能的方法之后,我最终找到了解决方案。发布以防万一有人偶然发现了这个问题。
我必须将 int requestCode 与通知 ID 相匹配。为什么?完全不知道...我只能假设它可以防止 Intent 数据变为 null 或重新使用它?
private static int ONGOING_NOTIFICATION_ID = 76;
PendingIntent contentIntent = PendingIntent.getActivity(this,
ONGOING_NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
与startForeground的通知id相同:
this.startForeground(ONGOING_NOTIFICATION_ID, not);
希望这对某人有帮助。
关于java - Activity 调用 finish() 时通知 pendingIntent contentIntent 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12509156/