Android-无法使用FirebaseMessagingService获取分组/捆绑通知

时间:2018-09-18 17:29:47

标签: java android firebase firebase-cloud-messaging

我有一个Firebase服务,可在数据消息上创建通知。

看起来像

public class KaliumMessagingService extends FirebaseMessagingService {
    private static final String TAG = KaliumMessagingService.class.getSimpleName();
    private static final String NOTIFICATION_CHANNEL_ID = "natrium_notification_channel";

    private final String NOTIF_GROUP_ID = "NATRIUM_NOTIF_GROUP";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData() != null && !MainActivity.appInForeground) {
            sendNotification(remoteMessage);
        }
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
        sharedPreferencesUtil.setFcmToken(token);
    }

    public void initChannels(Context context) {
        if (Build.VERSION.SDK_INT < 26) {
            return;
        }
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Natrium transaction alerts");
        notificationManager.createNotificationChannel(channel);
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        Map<String, String> data = remoteMessage.getData();
        String amount = data.get("amount");
        if (amount == null) {
            return;
        }

        initChannels(this);

        try (Realm realm = Realm.getDefaultInstance()) {
            Credentials c = realm.where(Credentials.class).findFirst();
            // If not logged in, shouldn't post notifications
            if (c == null) {
                return;
            }
        }

        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.drawable.ic_status_bar);
        builder.setContentText(getString(R.string.notification_body));
        builder.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)));
        builder.setAutoCancel(true);
        builder.setGroup(NOTIF_GROUP_ID);
        builder.setSound(defaultSoundUri);

        Notification pushNotification = builder.build();

        nm.notify((int)System.currentTimeMillis(), pushNotification);
    }
}

它可以工作,但是所有通知都是单独的。我希望它们都可以组合在一起/可扩展。然后单击它会打开主要活动并关闭所有通知。

我以为setGroup会达到这种效果,但似乎没有任何作用。

谢谢

1 个答案:

答案 0 :(得分:0)

I ended up solving it as described in this blog post

https://blog.hopbucket.com/merge-firebase-notifications-9f96de7d026a

public class KaliumMessagingService extends FirebaseMessagingService {
    private static final String TAG = KaliumMessagingService.class.getSimpleName();
    private static final String NOTIFICATION_CHANNEL_ID = "natrium_notification_channel";

    private int NOTIFICATION_ID = 1337;


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
        if (remoteMessage.getData() != null && !MainActivity.appInForeground && sharedPreferencesUtil.getNotificationSetting() != NotificationOption.OFF) {
            if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.M) {
                sendNotification(remoteMessage);
            } else {
                sendNotificationLegacy(remoteMessage);
            }
        }
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(this);
        sharedPreferencesUtil.setFcmToken(token);
    }

    public void initChannels(Context context) {
        if (Build.VERSION.SDK_INT < 26) {
            return;
        }
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                getString(R.string.app_name),
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Natrium transaction alerts");
        notificationManager.createNotificationChannel(channel);
    }

    private void sendNotificationLegacy(RemoteMessage remoteMessage) {
        Map<String, String> data = remoteMessage.getData();
        String amount = data.get("amount");
        if (amount == null) {
            return;
        }

        initChannels(this);

        try (Realm realm = Realm.getDefaultInstance()) {
            Credentials c = realm.where(Credentials.class).findFirst();
            // If not logged in, shouldn't post notifications
            if (c == null) {
                return;
            }
        }

        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.drawable.ic_status_bar);
        builder.setContentText(getString(R.string.notification_body));
        builder.setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)));
        builder.setAutoCancel(true);
        builder.setGroup(TAG);
        builder.setSound(defaultSoundUri);

        Notification pushNotification = builder.build();

        nm.notify((int)System.currentTimeMillis(), pushNotification);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void sendNotification(RemoteMessage remoteMessage) {
        Map<String, String> data = remoteMessage.getData();
        String amount = data.get("amount");
        if (amount == null) {
            return;
        }

        initChannels(this);

        try (Realm realm = Realm.getDefaultInstance()) {
            Credentials c = realm.where(Credentials.class).findFirst();
            // If not logged in, shouldn't post notifications
            if (c == null) {
                return;
            }
        }

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        Intent onCancelNotificationReceiver = new Intent(this, CancelNotificationReceiver.class);
        PendingIntent onCancelNotificationReceiverPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
                onCancelNotificationReceiver, 0);
        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())) {
                Intent startNotificationActivity = new Intent(this, MainActivity.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, NOTIFICATION_CHANNEL_ID)
                        .setSmallIcon(R.drawable.ic_status_bar)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)))
                        .setContentText(getString(R.string.notification_body))
                        .setAutoCancel(true)
                        .setStyle(getStyleForNotification(getString(R.string.notification_body)))
                        .setGroupSummary(true)
                        .setGroup(TAG)
                        .setContentIntent(pendingIntent)
                        .setDeleteIntent(onCancelNotificationReceiverPendingIntent)
                        .build();
                SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), getString(R.string.notification_body));
                editor.apply();
                notificationManager.notify(NOTIFICATION_ID, notification);
                return;
            }
        }
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Notification notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_status_bar)
                .setContentTitle(getString(R.string.notification_title, NumberUtil.getRawAsUsableString(amount)))
                .setContentText(getString(R.string.notification_body))
                .setAutoCancel(true)
                .setGroup(TAG)
                .setContentIntent(pendingIntent)
                .setDeleteIntent(onCancelNotificationReceiverPendingIntent)
                .build();
        SharedPreferences sharedPreferences = getSharedPreferences("NotificationData", 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(String.valueOf(new Random(NOTIFICATION_ID)), getString(R.string.notification_body));
        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(getString(R.string.notificaiton_header_suplement));
        return inbox;
    }
}