[英]How to send fcm notification when app is not running
我嘗試了很多解決方案,但沒有一個奏效。 我可以在應用程序處於活動狀態時收到 FCM 通知,但在應用程序處於后台或被終止時無法收到通知。
您需要創建一個擴展 FirebaseMessagingService 的服務類並覆蓋該類中的 onMessageReceived 方法以發送通知
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
try {
message.notification?.let {
showNotification(
it.title ?: "",
it.body ?: ""
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
您現在正在從后端獲取通知信息,並使用函數showNotification
將其顯示為通知。 當然,您必須實現函數showNotification
。 它只是一個簡單的功能,用於在 android 中顯示通知
編輯:這是函數的實現,將其添加到您的類中
class MyFirebaseMessagingService : FirebaseMessagingService() {
companion object {
const val channelId = "Channel"
const val channelName = "MyChannel"
const val smallIcon: Int = R.drawable.ic_logo
const val notificationId = 1
}
fun showNotification(myTitle: String, myBody: String) {
val notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(applicationContext, channelId)
} else {
Notification.Builder(applicationContext)
}
val intent = Intent(applicationContext, HomeActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
applicationContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationManager =
applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
when {
Build.VERSION.SDK_INT >= 26 -> {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
notificationBuilder
.setContentIntent(pendingIntent)
.setContentText(myBody)
.setSmallIcon(smallIcon)
.setContentTitle(myTitle)
}
Build.VERSION.SDK_INT >= 24 -> notificationBuilder
.setContentText(myBody)
.setContentTitle(myTitle)
.setSmallIcon(smallIcon)
.setContentIntent(pendingIntent)
else -> notificationBuilder
.setContentText(myBody)
.setContentTitle(myTitle)
.setSmallIcon(smallIcon)
.setContentIntent(pendingIntent)
}
notificationManager.notify(notificationId, notificationBuilder.build())
}
}
如果您想在應用程序處於后台或終止時收到通知,您的 json 對象必須是這樣的:
{ "data":{ "title": "your_title", "body": "your_body" }, "to": "device_token", "priority": "high" }
您可以在MessageReceived上捕捉通知
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.