關於發送多條notifications所遇到的一些問題
由於我需要開發的app是麵向特定人群使用的。服務器根據需要向用戶及時推送內容。可以認為每一條內容都很重要,並且客戶都希望我們能夠準確的推送。所以采用發送多條推送。也就是notification的ID 不能是一個定值, 本來我以為這個設置就OK了。結果發現到了一個情況:比如我發送了三條推送消息,每條消息都包含一個JSON數據, APP收到會顯示該JSON數據。現在碰到的問題是按照網上給的代碼。 如果三條信息都不點擊會發現 這三個notification隻包含一個Intent。 也就是你點擊一個會執行你期望的動作, 其他兩個失效了。最後查到stackoverflow上麵有人解決了這個問題, 就是給PendingIntent的getActivity()中的requestCode設置一個unique ID 就OK了 。附上鏈接: https://stackoverflow.com/questions/3009059/android-pending-intent-notification-problem
發送notifications的代碼
NotificationManager mNotificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Intent mIntent = new Intent(context, MainActivity.class); mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mIntent.putExtra(TAG, GCM); mIntent.putExtra(MESSAGE_ID, message_id); mIntent.putExtra(TITLE, title); mIntent.putExtra(TEXT, msg); int requestID = (int) System.currentTimeMillis(); PendingIntent contentIntent = PendingIntent.getActivity(context, requestID, mIntent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setContentTitle(title) .setContentText(msg) .setSmallIcon(R.drawable.ic_launcher) .setAutoCancel(true) .setLights(Color.parseColor("#2E6AD7"), 5000, 5000) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); mBuilder.setContentIntent(contentIntent); SharedPreferences prefs = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notifiId = prefs.getInt("notifiId_count", 0); notifiId = notifiId + 1; mNotificationManager.notify(notifiId,mBuilder.build()); SharedPreferences.Editor editor = prefs.edit(); editor.putInt("notifiId_count", notifiId); editor.commit();
最後更新:2017-04-03 14:53:58