我正在使用Firebase云函数发送通知。当我使用通知密钥发送有效负载时,通知会发送,但未调用方法。但是有了数据密钥,什么也没发生。
这是我的FirebaseMessagingService代码
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
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());
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String title, String messageBody){
String channelId = getString(R.string.default_notification_channel_id);
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);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 , notificationBuilder.build());
}
这是我的火力云函数
exports.sendNotification = functions.database
.ref("/deals/{userId}/{dealId}")
.onCreate((data, context) => {
const dataValue = data.val();
const topic = context.params.userId;
const payload = {
data: {
title: "New deal created",
body: dataValue.user.name + " added a new deal."
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
return admin
.messaging()
.send(payload)
.then(response => {
// Response is a message ID string.
console.log("Successfully sent message:", response);
})
.catch(error => {
console.log("Error sending message:", error);
});
});
我还在 onMessageReceived(( 上设置了一个调试点,但它没有被启动。
我想出了问题所在。问题是在进行一些更改并构建 android 项目后,我们需要再次订阅主题。
当您的应用在后台时,Firebase 不会触发 在消息接收,它将显示通知警报
+
确保您订阅了正确的主题
+
确保在您的设备上更新了 Play 服务。