Can't put extras for an intent in notification

余生颓废 提交于 2020-01-04 05:05:26

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/7098893/cant-put-extras-for-an-intent-in-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!