【发布时间】:2020-06-09 11:46:17
【问题描述】:
我正在使用我的 Java 后端向 Android 设备发送通知。
Android 设备收到通知,当我点击它时,它会打开我的应用程序。
到目前为止一切顺利,但我想要实现的是能够从 MainActivity 类的 onCreate() 方法中的 Firebase 消息中读取数据。这怎么可能?
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val channelId = "" // TODO CHANNEL ID NEEDED
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
这不会为我记录任何内容(在 onCreate() 中):
if (getIntent() != null) {
val dataBundle = getIntent().extras
Log.d("data bundle", dataBundle.toString())
}
【问题讨论】:
-
您如何从 Firebase 发送通知?您应该查看是否需要 getIntent() 的上下文。
-
如文档中建议的那样:firebase.google.com/docs/cloud-messaging/send-message#java 和
setNotification()
标签: android firebase push-notification notifications