Это код функции, который я развертываю в функции Firebase. :
Код: Выделить всё
const {onSchedule} = require("firebase-functions/v2/scheduler");
const admin = require("firebase-admin");
admin.initializeApp();
exports.sendReminderNotification = onSchedule(
{
schedule: "every 24 hours",
},
async (context) => {
const db = admin.firestore();
const oneDayAgo = admin.firestore.Timestamp.fromDate(
new Date(Date.now() - 24 * 60 * 60 * 1000)
);
const snapshot = await db.collection("user")
.where("lastLogin", " 24 hours.");
return null;
}
else{
const tokens = [];
snapshot.forEach((doc) => {
const userData = doc.data();
const token = userData.fcmToken;
const statusNotif = userData.status_notif;
const role = userData.role;
const statusUser = userData.status;
if (token && statusNotif == true && role == "user" && statusUser == true) {
tokens.push(token);
}
});
if(tokens.length > 0){
const payload = {
notification: {
title: "Reminder",
body: "Don't forget to open app!",
click_action: "MAIN_ACTIVITY_USER"
},
data: {
title: "Reminder",
body: "Don't forget to open app!",
},
};
const multicastMessage = {
tokens,
...payload,
};
try {
const response = await admin.messaging().sendEachForMulticast(multicastMessage);
console.log(`${response.successCount} notif success.`);
console.log(`${response.failureCount} notif fail.`);
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.error(`Token fail: ${tokens[idx]}, error: ${resp.error}`);
}
});
} catch (error) {
console.error("Failed to send notif multicast:", error);
}
}
else{
console.log("No users fit the requirement.");
return null;
}
}
});
AndroidManifest.xml:
Код: Выделить всё
Код: Выделить всё
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d("FCM", "Message from: ${remoteMessage.from}")
remoteMessage.data.isNotEmpty().let {
Log.d("FCM", "Data message payload: ${remoteMessage.data}")
sendNotification(remoteMessage.getData()["title"], remoteMessage.getData()["body"]);
}
remoteMessage.notification?.let {
Log.d("FCM", "Notification title: ${it.title}")
Log.d("FCM", "Notification body: ${it.body}")
sendNotification(it.title, it.body)
}
}
private fun sendNotification(messageTitle: String?, messageBody: String?) {
val channelId = "reminder_channel"
val notificationId = 1
val intent = Intent(this, MainActivityUser::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notif)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setStyle(NotificationCompat.BigTextStyle().bigText(messageBody))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
// for Android Oreo +
val channelName = "Reminder Channel"
val channelDescription = "Channel to remind user"
val channelImportance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, channelName, channelImportance).apply {
description = channelDescription
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.e("FCM", "Notification permission not granted")
return
}
Log.d("FCM", "Showing notif")
NotificationManagerCompat.from(this).notify(notificationId, notificationBuilder.build())
}
Проблема в том, что мне приходится использовать уведомление, чтобы напомнить пользователю, пока приложение закрыто, и я не понимаю, что пошло не так. Поскольку отправка данных работает отлично, почему не работает и уведомление?
Я знаю, что для уведомления не нужно использовать onMessageReceived, как для данных, и оно должно автоматически отображаться на панели, но это просто не так, и я думал и пытался несколько дней и недель, но до сих пор не понимаю, почему...
Буду очень признателен за помощь, пожалуйста
Подробнее здесь: https://stackoverflow.com/questions/792 ... e-function
Мобильная версия