我正在尝试在上传帖子时向应用程序的最终用户推送通知。当应用程序处于前台时,它工作正常,但当应用程序处于后台或被杀时,它不会显示。有没有办法在应用程序被杀死或在后台运行时显示通知。这是我正在使用的节点.js代码
const functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPush = functions.database.ref('/promos').onWrite(event => {
var topic = "deals_notification";
let projectStateChanged = false;
let projectCreated = false;
let projectData = event.data.val();
if (((event.data.numChildren())-(event.data.previous.numChildren()))>0) {
let msg="notification arrived"
let payload = {
notification: {
title: 'Firebase Notification',
body: msg,
sound: 'default',
badge: '1'
}
};
admin.messaging().sendToTopic(topic, payload).then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
}).catch(function(error) {
console.log("Error sending message:", error);
});
}
});
以下是MyFirebaseMessageService:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessageService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("notification---",remoteMessage.getNotification().getBody());
sendnotification(remoteMessage.getNotification().getBody());
}
private void sendnotification(String body){
Intent intent = new Intent(this, MainActivity.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, (int)
System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification.Builder n = new Notification.Builder(this)
.setContentTitle("Best Deals")
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, n.build());
}
}
谢谢。
代码是完美的。但是您正在测试的设备可能存在一些问题。请尝试使用其他设备测试代码。
如果问题是仅在应用程序处于前台时调用onMessageReceived()
,并且当它在后台时会显示通知但不调用您的方法......比这正常工作。请参阅文档:
如果您希望 FCM 处理显示 代表客户端应用的通知。在以下情况下使用数据消息 想要处理客户端应用上的消息。
在此处阅读更多内容: https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
您正在发送通知消息。相反,您应该发送数据消息
如果问题不同:当应用程序在后台没有任何反应时,可能是您的设备有问题。请参阅当应用程序被杀死时,使用 FCM 推送通知 android