gpt4 book ai didi

android - 通知未出现在应用程序的后台状态和终止状态

转载 作者:行者123 更新时间:2023-11-29 19:12:46 25 4
gpt4 key购买 nike

我正在尝试在上传帖子时向应用的最终用户推送通知。当应用程序处于前台时它工作正常但当应用程序处于后台或被杀死时不显示。当应用程序被终止或在后台运行时,有什么方法可以显示通知。这是我正在使用的 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());
}
}

谢谢。

最佳答案

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

关于android - 通知未出现在应用程序的后台状态和终止状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44680655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com