【发布时间】:2020-05-25 17:34:52
【问题描述】:
我想在我创建的频道中显示我的通知,以便我可以根据自己的喜好完全自定义我的频道。我正在使用 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);
}
}
我可以成功发送通知,但通知会转到杂项频道。
我尝试通过将频道 ID 与 notificationManager.deleteNotificationChannel("fcm_fallback_notification_channel"); 一起使用来删除频道,但它仍会重新创建频道并在那里发送通知。如何永久删除杂项频道并使用自己的频道处理通知?
【问题讨论】:
-
回答问题的标题:“如何避免向 Firebase 的 'Miscellaneous' 频道发送通知?” 为 FCM 消息设置默认频道,它们将发送到那里而不是
miscellaneous。
标签: javascript google-cloud-functions firebase-cloud-messaging android-notifications firebase-admin