Android通知的使用你可能會(huì)遇到的坑
最近使用android的通知遇到一些坑,都是以前不知道的問題。
先貼一段代碼
- /**
- * 創(chuàng)建通知欄管理工具
- */
- NotificationManager notificationManager = (NotificationManager) mContext.getSystemService
- (Context.NOTIFICATION_SERVICE);
- notificationManager.cancel(105);
- Intent equipListPage = new Intent(mContext, CommonActivity.class);
- equipListPage.putExtra("fragmentName", EquipListFragment.class.getName());
- equipListPage.putExtra("json", JSON.toJSONString(list));
- PendingIntent pi = PendingIntent.getActivity(mContext, 0, equipListPage, null);
- /**
- * 實(shí)例化通知欄構(gòu)造器
- */
- NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
- Notification notification = mBuilder
- .setAutoCancel(true)
- .setContentTitle("test")
- .setContentText("在你的周圍發(fā)現(xiàn) " + list.size() + " 個(gè)設(shè)備")
- .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(NotificationCompat.PRIORITY_MAX)
- .build();
- notifyId = (int) System.currentTimeMillis();
- notificationManager.notify(105, notification);
目的是通知告訴用戶周圍發(fā)現(xiàn)一些東西,然后用戶點(diǎn)開顯示一個(gè)列表。很快寫完代碼,測(cè)試了下ok。然后就發(fā)布了版本,但是用戶一直說每次點(diǎn)開的列表都是同一個(gè),讓我很費(fèi)解,一直以為不是自己的問題,***自己試了試,好尷尬。果然有問題,就是傳遞的數(shù)據(jù)沒有被更新。
如何解決的
問題在于這一句
- PendingIntent.getActivity(mContext, 0, equipListPage, null);
一共有四個(gè)參數(shù),看看源碼的解釋
- * @param context The Context in which this PendingIntent should start
- * the activity.
- * @param requestCode Private request code for the sender
- * @param intent Intent of the activity to be launched.
- * @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
- * {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
一共有四個(gè)FLAG_ONE_SHOT 、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT
我使用的是FLAG_UPDATE_CURRENT解決了問題,它主要是用來更新消息,比如你發(fā)送了一個(gè)通知消息,傳遞“123” ,在點(diǎn)擊前有發(fā)送了一個(gè)通知消息,推送的是“345”,此時(shí)你點(diǎn)擊兩條消息,都是得到的“345”。 所以我的問題自然就解決了。
問題二
后面又來了一個(gè)需求,需要增加一個(gè)通知消息,展示不一樣的應(yīng)用。 也就是上面的消息,通知1 需要得到“123”,通知2需要得到“456” 。 這該怎么辦呢,這就需要用到第二個(gè)flag了 。當(dāng)使用FLAG_CANCEL_CURRENT時(shí),依然是上面的操作步驟,這時(shí)候會(huì)發(fā)現(xiàn),點(diǎn)擊消息1時(shí),沒反應(yīng),第二條可以點(diǎn)擊。原因在于第二個(gè)參數(shù),你需要每個(gè)不同的消息,定義不同的requestCode ,問題就能夠得到解決。