Android通知的使用你可能會遇到的坑
最近使用android的通知遇到一些坑,都是以前不知道的問題。
先貼一段代碼
- /**
- * 創建通知欄管理工具
- */
- 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);
- /**
- * 實例化通知欄構造器
- */
- NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
- Notification notification = 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(NotificationCompat.PRIORITY_MAX)
- .build();
- notifyId = (int) System.currentTimeMillis();
- notificationManager.notify(105, notification);
目的是通知告訴用戶周圍發現一些東西,然后用戶點開顯示一個列表。很快寫完代碼,測試了下ok。然后就發布了版本,但是用戶一直說每次點開的列表都是同一個,讓我很費解,一直以為不是自己的問題,***自己試了試,好尷尬。果然有問題,就是傳遞的數據沒有被更新。
如何解決的
問題在于這一句
- PendingIntent.getActivity(mContext, 0, equipListPage, null);
一共有四個參數,看看源碼的解釋
- * @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},
一共有四個FLAG_ONE_SHOT 、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLAG_UPDATE_CURRENT
我使用的是FLAG_UPDATE_CURRENT解決了問題,它主要是用來更新消息,比如你發送了一個通知消息,傳遞“123” ,在點擊前有發送了一個通知消息,推送的是“345”,此時你點擊兩條消息,都是得到的“345”。 所以我的問題自然就解決了。
問題二
后面又來了一個需求,需要增加一個通知消息,展示不一樣的應用。 也就是上面的消息,通知1 需要得到“123”,通知2需要得到“456” 。 這該怎么辦呢,這就需要用到第二個flag了 。當使用FLAG_CANCEL_CURRENT時,依然是上面的操作步驟,這時候會發現,點擊消息1時,沒反應,第二條可以點擊。原因在于第二個參數,你需要每個不同的消息,定義不同的requestCode ,問題就能夠得到解決。