菜鸟学android——Notification、PendingIntent问题

来源:互联网 发布:新开户数据 编辑:程序博客网 时间:2024/05/28 11:48

先描述一下我遇到的问题吧:

后台服务有可能会发送3种通知信息,均指向同一个Activity,只是Intent中所带的信息不一样。当3个通知同时出现时,问题就来了,点击通知,打印Intent所带的信息,发现都一样!

具体看下发送通知的代码:

private void sendNotification(int id) {Intent intent = new Intent(BBSService.this, BBSListActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);if (id == BBS_REPLY_ID) {intent.putExtra("reply", true);intent.putExtra("at", false);intent.putExtra("mail", false);} else if (id == BBS_AT_ID) {intent.putExtra("reply", false);intent.putExtra("at", true);intent.putExtra("mail", false);} else if (id == BBS_MAIL_ID) {intent.putExtra("reply", false);intent.putExtra("at", false);intent.putExtra("mail", true);}intent.putExtra("id", id);Notification BBSNotification = new Notification();BBSNotification.icon = R.drawable.ic_launcher;BBSNotification.tickerText = "爱邮";BBSNotification.when = System.currentTimeMillis();BBSNotification.defaults = Notification.DEFAULT_SOUND;BBSNotification.defaults |= Notification.DEFAULT_VIBRATE;BBSNotification.flags |= Notification.FLAG_AUTO_CANCEL;PendingIntent mobilePi = PendingIntent.getActivity(BBSService.this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);if (id == BBS_REPLY_ID) {BBSNotification.setLatestEventInfo(BBSService.this, "论坛消息","新回复我的文章件", mobilePi);} else if (id == BBS_AT_ID) {BBSNotification.setLatestEventInfo(BBSService.this, "论坛消息","新@我的文章", mobilePi);} else if (id == BBS_MAIL_ID) {BBSNotification.setLatestEventInfo(BBSService.this, "论坛消息", "新邮件",mobilePi);}notificationManager.notify(id, BBSNotification);}

通过深入了解,大概明白问题在哪里了。

PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags)方法并不能保证每次返回的PendingIntent都是一个新的。如果这个PendingIntent已经存在,那么就会按照flags位的设置对intent进行处理,我这里用的是PendingIntent.FLAG_UPDATE_CURRENT,那么每次都会更新intent,也就是说如果发送了3个通知,那么他们所携带的intent都会是最后一次更新的那个intent。

明白了问题所在,那么解决方法就呼之欲出了,只要保证PengdingIntent的配置不同,那么getActivity返回的必然就是新的PendingIntent。这里把requestCode值定义为id值,就可以了。


0 0
原创粉丝点击