Как избежать отправки уведомлений на канал «Разное» на Firebase? - PullRequest
1 голос
/ 10 февраля 2020

Я хочу показывать свои уведомления в канале, который я создаю, чтобы я мог полностью настроить свой канал с моими предпочтениями. Я использую функцию Firebase для отправки уведомлений (сообщений) от пользователя к пользователю:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.firestore.document('/devices/{tokenId}/notifications/{notificationId}')
    .onWrite((change, context) => {
        console.log('Push notification event triggered');

        const tokenId = context.params.tokenId;
        const document = change.after.exists ? change.after.data() : null;

        if (document == null) {
            return console.log('A notification has been deleted from database');
        }

        const payload = {
            notification: {
                title: document.username,
                body: document.message,
                sound: "default"
            },
            data: {
                sender: document.sender
            }
        };
        const options = {
            priority: "high",
            timeToLive: 60 * 60 * 24 //24 hours
        };

        return admin.messaging().sendToDevice(tokenId, payload, options).then(result => {
            console.log('A notification sent to device with tokenId: ', tokenId);
        });
    });

Я реализовал свой сервис FirebaseMessagingService:

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    showNotification(remoteMessage);
}

private void showNotification(RemoteMessage remoteMessage) {
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    RemoteMessage.Notification remoteNotification = remoteMessage.getNotification();
    if (remoteNotification == null) return;
    String title = remoteNotification.getTitle();
    String message = remoteNotification.getBody();

    Notification notification;
    Notification.Builder builder = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
            new Notification.Builder(this, CH_MESSAGE) : new Notification.Builder(this);

    notification = builder
            .setContentTitle(title)
            .setContentText(message)
            .setCategory(CATEGORY_MESSAGE)
            .build();

    notificationManager.notify(0, notification);
}

И создал свой собственный канал уведомлений на Класс моего приложения:

@Override
public void onCreate() {
    super.onCreate();
    createNotificationChannels();
}

private void createNotificationChannels() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (notificationManager == null) return;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CH_MESSAGE,
                getString(R.string.messages), NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription(getString(R.string.message_channel_description));

        notificationManager.createNotificationChannel(notificationChannel);
    }
}

Я могу успешно отправлять уведомления, но уведомления отправляются на Разный канал.

Screenshot

Я пытался удалить канал, используя его идентификатор канала с notificationManager.deleteNotificationChannel("fcm_fallback_notification_channel");, но он все равно воссоздает канал и отправляет уведомление туда. Как я могу навсегда удалить канал «Разное» и обрабатывать свои уведомления своими собственными каналами?

1 Ответ

1 голос
/ 10 февраля 2020

Я обнаружил проблему, с которой сталкиваюсь, полезная нагрузка моего сообщения содержит поля уведомлений и данных. Согласно этой документации мои сообщения не вызывали метод onMessageReceived, когда приложение находится в фоновом режиме. Теперь я использую только полезную нагрузку данных, которая вызывает метод, когда приложение находится как на заднем, так и на переднем плане.

const payload = {
    data: {
        sender: document.sender,
        username: document.username,
        message: document.message
    }
};

А в моем методе onMessageReceived:

Map<String, String> remoteMap = remoteMessage.getData();
String senderUid = remoteMap.get("sender");
String senderUsername = remoteMap.get("username");
String message = remoteMap.get("message");

Notification.Builder builder = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ?
        new Notification.Builder(this, CH_MESSAGE) : new Notification.Builder(this);

Notification notification = builder
        .setContentTitle(senderUsername)
        .setContentText(message)
        .setSmallIcon(R.drawable.ic_notif_message)
        .build();

notificationManager.notify(0, notification);
...