最近大家在使用Android通知时遇到了一些坑,都是以前不知道的问题。先贴一段代码/***创建通知栏管理工具*/NotificationManagernotificationManager=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);notificationManager.cancel(105);IntentequipListPage=newIntent(mContext,CommonActivity.class);equipListPage.putExtra("fragmentName",EquipListFragment.class.getName());equipListPage.putExtra("json",JSON.toJSONString(list));PendingIntentpi=PendingIntent.getActivity(mContext,0,equipListPage,null);/***示例通知栏构造函数*/NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(mContext);Notificationnotification=mBuilder.setAutoCancel(true).setContentTitle("test").setContentText("发现你身边"+list.size()+"设备”).setContentIntent(pi).setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.max_ic_launcher)).setSmallIcon(R.drawable.max_ic_launcher).setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_SOUND).setPriority(通知nCompat.PRIORITY_MAX).build();notifyId=(int)System.currentTimeMillis();notificationManager.notify(105,notification);目的是通知用户发现周围有东西,然后用户点击显示一个列表来赶紧写代码,测试ok。然后发布了版本,但是用户一直说每次打开列表都是一样的,让我很纳闷。一直以为不是我的问题,自己试了一下,好尴尬。果然有问题,就是传过来的数据没有更新。如何解决问题就在于这句PendingIntent.getActivity(mContext,0,equipListPage,null);一共有四个参数,看源码解释*@paramcontextTheContext在whichthisPendingIntentshouldstart*theactivity.*@paramrequestCodePrivaterequestcodeforthesender*@paramintentIntentoftheactivitytobelaunched.*@paramflagsMaybe{#FLAG_ONE_SHOT},{@link#FLAG_NO_CREATE},*{@link#FLAG_CANCEL_CURRENT},{@link#FLAG_UPDATE_CURRENT},有四个FLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT,FLAG_UPDATE_CURRENT我用FLAG_UPDATE_CURRENT来解决,主要是为了更新消息,比如你发一个通知消息,传"123",点击前发送通知消息,推送为“345”。这时,你点击两条消息,得到“345”。这样我的问题自然就解决了。问题2之后出现了另一个需求,即需要添加通知消息以显示不同的应用程序。也就是上面的消息,通知1需要得到“123”,通知2需要得到“456”。怎么办,这就需要用到第二个flag了。使用FLAG_CANCEL_CURRENT时,还是上面的操作步骤。这时候你会发现点击消息1没有任何反应,可以点击第二条消息。原因是对于第二个参数,需要为每个不同的消息定义不同的requestCode,问题就可以解决了。
