FCM 通知未在 android 的前台显示
Posted
技术标签:
【中文标题】FCM 通知未在 android 的前台显示【英文标题】:FCM Notification are not showing in foreground in android 【发布时间】:2022-01-06 02:28:19 【问题描述】:通知在后台显示,但当应用程序在前台时,通知不显示。我应用了许多解决方案,但它们对我不起作用。谁能告诉我我的错误在哪里?提前致谢
这是清单
<service
android:exported="false"
android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/cute" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/design_default_color_on_primary" />
这是我的 ServicesClass
const val cannelId = "notification_channel"
const val channel_name = "com.dextrologix.dham.rfms.resident.services"
class MyFirebaseMessagingService : FirebaseMessagingService()
override fun onMessageReceived(remoteMessage: RemoteMessage)
if (remoteMessage.notification != null)
genrateNotification(
remoteMessage.notification!!.title!!,
remoteMessage.notification!!.body!!
)
@SuppressLint("RemoteViewLayout")
fun getRemoteView(title: String, message: String): RemoteViews
val remteViews = RemoteViews(
"com.dextrologix.dham.rfms.resident.services",
R.layout.pushnotification_layout
)
remteViews.setTextViewText(R.id.notification_title, title)
remteViews.setTextViewText(R.id.notification_message, message)
remteViews.setImageViewResource(R.id.notification_image, R.drawable.cute)
return remteViews
fun genrateNotification(title: String, message: String)
var intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
var builder: NotificationCompat.Builder =
NotificationCompat.Builder(applicationContext, cannelId)
.setSmallIcon(R.drawable.person_icon)
.setAutoCancel(true)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
builder = builder.setContent(getRemoteView(title, message))
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val notificationChannel =
NotificationChannel(cannelId, channel_name, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
notificationManager.notify(0, builder.build())
【问题讨论】:
【参考方案1】:您似乎缺少通知渠道。它们是 android 通知所必需的。 docs link
【讨论】:
感谢您的回答。我已经编辑了我的代码,但它仍然无法在前台工作 有错误吗?你能仔细检查你的 google_services.json 吗? 不,没有错误。当我在 onMessageReceived() 中添加调试器或 toast 时,什么都没有显示.. 我认为我的函数没有在任何地方调用 不是,但它会监听来自 FCM 的推送。您确定 googleServices.json 在正确的位置并且配置正确吗?如果不是,它应该在 logcat 中显示 waкnings,例如 googleServices not found/not configured 等以上是关于FCM 通知未在 android 的前台显示的主要内容,如果未能解决你的问题,请参考以下文章