通知不会出现在应用程序的背景状态和死亡状态

我试图在上传post时将通知推送给应用的最终用户。 它在应用程序处于前景时工作正常,但当应用程序在后台或被杀害时不显示。 有什么办法来显示应用程序被杀害或在后台运行的通知。 这里是我使用的node.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()); } } 

谢谢。

我相信代码是完美的。 但是您正在testing的设备可能存在一些问题。请尝试使用其他设备testing代码。

如果问题是onMessageReceived()只在应用程序处于前台时被调用,并且在后台时会显示通知,但是您的方法不会被调用…而不是正常工作。 请参阅文档:

当您希望FCM代表客户端应用程序显示通知时使用通知消息。 当您想要处理客户端应用程序中的消息时使用数据消息。

请阅读更多信息: https : //firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

您正在发送通知消息。 相反,你应该发送一个数据消息

如果问题不同:当应用程序在后台没有任何事情发生,这可能是您的设备的问题。 请参阅使用FCM推送通知没有收到应用程序被杀死Android