У меня есть приложение для Android, которое успешно получает уведомления от консоли Firebase. Теперь я намереваюсь создать сервер nodejs, куда мы можем отправлять эти уведомления для сохранения регистрации в консоли firebase, однако, похоже, что библиотека firebase-admin для node.js поддерживает отправку только на отдельные идентификаторы устройств или разделы, а не на все устройства. согласно консоли.
Итак, я создал службу nodejs для отправки в тему «all» и попытался изменить Android для получения этих уведомлений, однако я не получаю уведомления на свое устройство с этого сервера nodejs.
Вот мой код сервера:
var admin = require("firebase-admin");
var serviceAccount = require("./firebase-privatekey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://myapp-android-xxx.firebaseio.com"
});
var payload = {
notification: {
title: "Account Deposit",
body: "A deposit to your savings account has just cleared."
},
data: {
account: "Savings",
balance: "$3020.25"
},
topic: "all",
};
admin.messaging().send(payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
Это код Android, который работал с уведомлениями консоли:
public class MyNotificationService extends FirebaseMessagingService {
public MyNotificationService() {
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Firebase", "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("Firebase", "Message data payload: " + remoteMessage.getData());
handleNow(remoteMessage.getData(), remoteMessage.getNotification().getBody());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d("Firebase", "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
public void handleNow(Map<String, String> data, String title) {
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.myapp_notification_icon)
.setBadgeIconType(R.drawable.myapp_notification_icon)
.setContentTitle(title)
.setContentText(data.get("information"));
notificationManager.notify(notificationId, mBuilder.build());
}
}
и это новый (дополнительный, не замененный) код с намерением получать тематические сообщения:
@Override
protected void onCreate(Bundle savedInstanceState) {
//other code...
FirebaseMessaging.getInstance().subscribeToTopic("all")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
System.out.println("win");
} else {
System.out.println("fail");
}
}
});
}
Сервер nodejs сообщает мне, что это была успешная отправка сообщения, но точка останова в сообщении о победе или неудаче никогда не попадает на Android