我是Firebase云功能和fcm的新手,我的情况是每当数据库中发布新文章时,我都需要向我的应用程序用户显示通知。
firebase云功能运行正常,但设备android未收到通知。
云功能
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Vacancy/{articleId}')
.onWrite((event: { after: any; }) => {
console.log("Successfully sent message:2");
var eventSnapshot = event.after;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
return admin.messaging().sendToTopic(topic, payload)
.then(function (response: any) {
console.log("Successfully sent message:", response);
})
.catch(function (error: any) {
console.log("Error sending message:", error);
});
});
显示代码
<service
android:name=".ServiceNotification.NotificationMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
NotificationMessagingService类代码
public class NotificationMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
FirebaseMessaging.getInstance().subscribeToTopic("android");
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("author"));
}
if (remoteMessage.getNotification() != null) {
}
}
private void showNotification(String title, String author) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Article: " + title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("By " + author)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
云功能日志
1:33:46.257 AM
sendNotification
Successfully sent message:2
1:33:46.263 AM
sendNotification
Author is Raja
1:33:47.022 AM
sendNotification
Successfully sent message: { messageId: 5711725841493019000 }
1:33:47.040 AM
sendNotification
Function execution took 1005 ms, finished with status: 'ok'