Как объединить push-уведомления, как это делает WhatsApp, в FirebaseMessagingService

Как объединить push-уведомления в FirebaseMessagingService. Я пробовал почти все, но ничего не работает. Для каждого нового объекта данных выдается новое уведомление. Журнал, в котором я печатаю количество уведомлений, печатает 0.

Есть ли какой-либо способ, с помощью которого я могу отслеживать, есть ли какое-либо непрочитанное уведомление в ящике уведомлений с тем же идентификатором уведомления, чтобы я мог объединить с ним новое?

Любая помощь будет оценена.

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());
        }}

comment
я также хочу объединить более одного push-уведомления из облачных сообщений Firebase. но не получая никакого способа сделать это.   -  person Gulnaz Ghanchi    schedule 06.01.2017
comment
@GulnazGhanchi взгляните на мой ответ и дайте мне знать, работает ли он для вас.   -  person Chetan Ashtivkar    schedule 07.01.2017


Ответы (1)


Поскольку никто не опубликовал ответ на этот вопрос, я сам придумал ответ. Это может быть не самый оптимизированный способ объединения уведомлений, но он сработал для меня как шарм. Взгляните на мою запись в блоге.

Вот мой класс FirebaseMessagingService:

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();
}}

Пожалуйста, не стесняйтесь предлагать любые изменения, чтобы я мог оптимизировать его дальше. Кроме того, если есть лучший способ сделать это, пожалуйста, напишите его ниже. Надеюсь, это поможет кому-то.

person Chetan Ashtivkar    schedule 07.01.2017
comment
Спасибо, что вернулись к своим вопросам. Однако ответы только по ссылкам не приветствуются. Пожалуйста, включите соответствующую информацию прямо здесь, на SO. Конечно, не стесняйтесь сохранять ссылку на свой пост. - person Eiko; 07.01.2017
comment
@Eiko Я включил необходимые фрагменты кода, спасибо за совет. - person Chetan Ashtivkar; 07.01.2017
comment
@ChetanAshtivkar getStyleForNotification можно упростить, вы берете записи из SharedPrefs в хэш-карту, а затем снова в другую хэш-карту, где вы можете просто просто добавить строки из значений напрямую. - person Pierre; 02.02.2018
comment
@ChetanAshtivkar не ясно, общие настройки открыли уведомление ... пожалуйста, помогите мне .. - person Pankaj Talaviya; 19.11.2019