首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android状态栏通知-意图在第二次获取旧的附加组件

Android状态栏通知-意图在第二次获取旧的附加组件
EN

Stack Overflow用户
提问于 2012-02-09 17:49:30
回答 2查看 8.1K关注 0票数 19

当我创建一个通过C2DM发送并在我的应用程序中接收的通知时,我希望在intent附加中传递来自C2DM的推送通知的一些数据。当我第一次打开我的通知时,它工作得很好。然后,根据活动的状态,使用onNewIntent或onCreate接收数据。

但是,如果我通过C2DM发送第二个推送通知,新数据会正确接收到它,但是当从intent获取额外的数据时,我仍然会从前一条消息中获取数据。我想要查看的标题和数据在通知中正确显示。所以一定是我的意图出了问题。如果活动正在运行,或者没有运行,就会发生这种情况。

要创建通知,我执行以下操作:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_stat_notify_push, "Message received", System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults |= Notification.DEFAULT_LIGHTS;
Intent intent = new Intent(context, DesktopApp.class);
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("msg_id", msg_id);
intent.putExtra("title", title);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, "New message", title + String.valueOf(msg_id), pendingIntent);
notificationManager.notify(0, notification);

然后阅读意图:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent myIntent = getIntent(); // this is just for example purpose
    int i = myIntent.getIntExtra("msg_id", -1);
    if (i != -1) Toast.makeText(this, "Got message! " + String.valueOf(i), Toast.LENGTH_LONG).show();
}


@Override
public void onNewIntent(Intent intent){
    super.onNewIntent(intent);
    Bundle extras = intent.getExtras();
    if (extras != null) {
        int i = extras.getInt("msg_id", -1);
        if (i != -1) Toast.makeText(this, "Got message! " + String.valueOf(i), Toast.LENGTH_LONG).show();
    }
}

有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-09 17:54:24

您需要为PendingIntent设置一个干净的标志:

PendingIntent pintent = 
   PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

看一看at this post,它给出了更长的解释。

票数 37
EN

Stack Overflow用户

发布于 2012-02-24 16:18:01

使用这个

PendingIntent pi = PendingIntent.getActivity(context, UNIQUE_ID, 
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9208547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档