如何像 whatsapp 在 FirebaseMessagingService 中那样合并推送通知
How to merge push notifications like whatsapp does in FirebaseMessagingService
如何在 FirebaseMessagingService 中合并推送通知。我几乎尝试了一切,但似乎没有任何效果。对于每个新的数据对象,它都会发出一个新的通知。我打印通知数量的日志打印 0.
有什么方法可以跟踪通知抽屉中是否有任何具有相同 notificationId 的未读通知,以便我可以将新通知与其合并?
任何帮助将不胜感激。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final String actionLiked = "liked";
mNumber=0;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
ArrayList<String>notificationString= new ArrayList<>();
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Log.d(TAG, "Number of notifications" +mNumber);
Map<String, String> dataFromCloud = remoteMessage.getData();
String action = dataFromCloud.get("action");
switch (action) {
case actionLiked:
notificationString.add(action);
Intent intent = new Intent(this, MainActivity.class);
sendNotification(action, intent);
break;
default:
break;
}
}
}
private void sendNotification(String messageTitle, Intent intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String[] events = new String[6];
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setNumber(++numMessages);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i=0; i < notificationString.size(); i++) {
inboxStyle.addLine(notificationString.get(i));
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
由于没有人回答这个问题,所以我自己想出了一个答案。这可能不是合并通知的最优化方式,但它对我来说就像一个魅力。看看 my blog post.
这是我的 FirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final String actionLiked = "liked";
private static final int NOTIFICATION_ID = 1593;
private final String GROUP_KEY = "GROUP_KEY_RANDOM_NAME";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
ArrayList<String> notificationString = new ArrayList<>();
if (remoteMessage.getData().size() > 0) {
Map<String, String> dataFromCloud = remoteMessage.getData();
String action = dataFromCloud.get("action");
String userName = dataFromCloud.get("userName");
switch (action) {
case actionLiked:
notificationString.add(action);
Intent intent = new Intent(this, LikeActivity.class);
String message = userName + " liked your photo.";
sendNotification(message, intent);
break;
default:
break;
}
}
}
@TargetApi(Build.VERSION_CODES.M)
private void sendNotification(String messageBody, Intent intent) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
Intent onCancelNotificationReceiver = new Intent(this, CancelNotificationReceiver.class);
PendingIntent onCancelNotificationReceiverPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
onCancelNotificationReceiver, 0);
String notificationHeader = this.getResources().getString(R.string.app_name);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (int i = 0; i < notifications.length; i++) {
if (notifications[i].getPackageName().equals(getApplicationContext().getPackageName())) {
Log.d("Notification", notifications[i].toString());
Intent startNotificationActivity = new Intent(this, NotificationCenterActivity.class);
startNotificationActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, startNotificationActivity,
PendingIntent.FLAG_ONE_SHOT);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(notificationHeader)
.setContentText("Tap to open")
.setAutoCancel(true)
.setStyle(getStyleForNotification(messageBody))
.setGroupSummary(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), messageBody);
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notification);
return;
}
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Notification notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(notificationHeader)
.setContentText(messageBody)
.setAutoCancel(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), messageBody);
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notificationBuilder);
}
private NotificationCompat.InboxStyle getStyleForNotification(String messageBody) {
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
SharedPreferences sharedPref = getSharedPreferences("NotificationData", 0);
Map<String, String> notificationMessages = (Map<String, String>) sharedPref.getAll();
Map<String, String> myNewHashMap = new HashMap<>();
for (Map.Entry<String, String> entry : notificationMessages.entrySet()) {
myNewHashMap.put(entry.getKey(), entry.getValue());
}
inbox.addLine(messageBody);
for (Map.Entry<String, String> message : myNewHashMap.entrySet()) {
inbox.addLine(message.getValue());
}
inbox.setBigContentTitle(this.getResources().getString(R.string.app_name))
.setSummaryText("Tap to open");
return inbox;
}
}
当用户点击通知或删除通知时,从共享首选项中清除保存的数据。为此,创建一个广播接收器,它将清除您保存的所有数据。在可以从通知打开的活动的 onCreate 中调用它。
广播接收器代码如下
public class CancelNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}}
请随时提出任何修改建议,以便我进一步优化。另外,如果有更好的方法,请在下面写下来。
希望这会对某人有所帮助。
如何在 FirebaseMessagingService 中合并推送通知。我几乎尝试了一切,但似乎没有任何效果。对于每个新的数据对象,它都会发出一个新的通知。我打印通知数量的日志打印 0.
有什么方法可以跟踪通知抽屉中是否有任何具有相同 notificationId 的未读通知,以便我可以将新通知与其合并?
任何帮助将不胜感激。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final String actionLiked = "liked";
mNumber=0;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
ArrayList<String>notificationString= new ArrayList<>();
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Log.d(TAG, "Number of notifications" +mNumber);
Map<String, String> dataFromCloud = remoteMessage.getData();
String action = dataFromCloud.get("action");
switch (action) {
case actionLiked:
notificationString.add(action);
Intent intent = new Intent(this, MainActivity.class);
sendNotification(action, intent);
break;
default:
break;
}
}
}
private void sendNotification(String messageTitle, Intent intent) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String[] events = new String[6];
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setNumber(++numMessages);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i=0; i < notificationString.size(); i++) {
inboxStyle.addLine(notificationString.get(i));
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
由于没有人回答这个问题,所以我自己想出了一个答案。这可能不是合并通知的最优化方式,但它对我来说就像一个魅力。看看 my blog post.
这是我的 FirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final String actionLiked = "liked";
private static final int NOTIFICATION_ID = 1593;
private final String GROUP_KEY = "GROUP_KEY_RANDOM_NAME";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
ArrayList<String> notificationString = new ArrayList<>();
if (remoteMessage.getData().size() > 0) {
Map<String, String> dataFromCloud = remoteMessage.getData();
String action = dataFromCloud.get("action");
String userName = dataFromCloud.get("userName");
switch (action) {
case actionLiked:
notificationString.add(action);
Intent intent = new Intent(this, LikeActivity.class);
String message = userName + " liked your photo.";
sendNotification(message, intent);
break;
default:
break;
}
}
}
@TargetApi(Build.VERSION_CODES.M)
private void sendNotification(String messageBody, Intent intent) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
Intent onCancelNotificationReceiver = new Intent(this, CancelNotificationReceiver.class);
PendingIntent onCancelNotificationReceiverPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
onCancelNotificationReceiver, 0);
String notificationHeader = this.getResources().getString(R.string.app_name);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (int i = 0; i < notifications.length; i++) {
if (notifications[i].getPackageName().equals(getApplicationContext().getPackageName())) {
Log.d("Notification", notifications[i].toString());
Intent startNotificationActivity = new Intent(this, NotificationCenterActivity.class);
startNotificationActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, startNotificationActivity,
PendingIntent.FLAG_ONE_SHOT);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(notificationHeader)
.setContentText("Tap to open")
.setAutoCancel(true)
.setStyle(getStyleForNotification(messageBody))
.setGroupSummary(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), messageBody);
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notification);
return;
}
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Notification notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(notificationHeader)
.setContentText(messageBody)
.setAutoCancel(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setDeleteIntent(onCancelNotificationReceiverPendingIntent)
.build();
SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), messageBody);
editor.apply();
notificationManager.notify(NOTIFICATION_ID, notificationBuilder);
}
private NotificationCompat.InboxStyle getStyleForNotification(String messageBody) {
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
SharedPreferences sharedPref = getSharedPreferences("NotificationData", 0);
Map<String, String> notificationMessages = (Map<String, String>) sharedPref.getAll();
Map<String, String> myNewHashMap = new HashMap<>();
for (Map.Entry<String, String> entry : notificationMessages.entrySet()) {
myNewHashMap.put(entry.getKey(), entry.getValue());
}
inbox.addLine(messageBody);
for (Map.Entry<String, String> message : myNewHashMap.entrySet()) {
inbox.addLine(message.getValue());
}
inbox.setBigContentTitle(this.getResources().getString(R.string.app_name))
.setSummaryText("Tap to open");
return inbox;
}
}
当用户点击通知或删除通知时,从共享首选项中清除保存的数据。为此,创建一个广播接收器,它将清除您保存的所有数据。在可以从通知打开的活动的 onCreate 中调用它。
广播接收器代码如下
public class CancelNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = context.getSharedPreferences("NotificationData", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}}
请随时提出任何修改建议,以便我进一步优化。另外,如果有更好的方法,请在下面写下来。 希望这会对某人有所帮助。