无法在通知中添加额外的意图

发布于 2024-11-30 03:33:54 字数 809 浏览 1 评论 0原文

我正在从具有额外整数意图的服务创建通知。出于某种原因,这并不像看起来那么容易。这就是我正在做的事情:

Notification notification = new Notification(R.drawable.notification_icon, "Title", 0);
Intent relaunchIntent = new Intent(this, SomeClass.class);
relaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
relaunchIntent.putExtra("load", getId());
notification.setLatestEventInfo(this, "Title", "Tap here to open", PendingIntent.getActivity(this, 0, relaunchIntent, 0);
notificationManager.notify(1234, notification);

然后从 SomeClass 中,它读起来像这样...

if(getIntent().getExtras() != null)
    load(getIntent().getExtras().getInt("load", -1));

奇怪的是,当我从 getInt() 方法读取值时,我得到不一致的结果。有时我会得到我在之前的通知中设置的值。例如,当我将额外值设置为 4 时,我得到的值是 3。我知道这非常令人困惑和奇怪,这就是为什么我想知道是否有人经历过这样的事情以及您可能已经采取了哪些措施来修复它。谢谢!

I'm creating a notification from a Service that has an intent with an extra integer. For some reason, this isn't as easy as it seems. This is what I'm doing:

Notification notification = new Notification(R.drawable.notification_icon, "Title", 0);
Intent relaunchIntent = new Intent(this, SomeClass.class);
relaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
relaunchIntent.putExtra("load", getId());
notification.setLatestEventInfo(this, "Title", "Tap here to open", PendingIntent.getActivity(this, 0, relaunchIntent, 0);
notificationManager.notify(1234, notification);

And then from SomeClass, it reads like this...

if(getIntent().getExtras() != null)
    load(getIntent().getExtras().getInt("load", -1));

What's weird is that I get inconsistent results when I read the value from the getInt() method. Sometimes I get values of things I set in a previous notifications. For example, I get a value of 3 when I had set that extra to be 4. I know this is very confusing and strange, which is why I'm wondering if anyone has experienced anything like this and what you may have done to fix it. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傾旎 2024-12-07 03:33:54

您应该尝试使用 PendingIntent.FLAG_UPDATE_CURRENT 当您调用 PendingIntent.getActivity 时。从文档中:

如果您要创建只有额外内容的意图,则可以使用此选项
更改,并且不关心任何收到您之前的实体
PendingIntent 将能够使用您的新附加功能启动它,即使
他们没有明确给出。

我自己遇到了这个问题,并从 这个答案

You should try using PendingIntent.FLAG_UPDATE_CURRENT when you call PendingIntent.getActivity. From the documentation:

This can be used if you are creating intents where only the extras
change, and don't care that any entities that received your previous
PendingIntent will be able to launch it with your new extras even if
they are not explicitly given to it.

I ran into this issue myself, and found the answer from a comment on this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文