Я пытаюсь сохранить уведомление Firebase в Room Dao, когда приложение в фоновом режиме. Отправлять уведомления почтальону, но полученное onMessage вызывается, только когда приложение находится на переднем плане, а сообщение имеет notification : {}
тело. Может ли кто-нибудь помочь мне с этой проблемой, пожалуйста: 3
Моя реализация FirebaseMessagingService:
class NotificationService : FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
val title = p0.notification?.title ?: return
val message = p0.notification?.body ?: return
Log.e("TAG","Notification: $title: $message")
Log.e("TAG","Data from notification : ${p0.data["key_1"]}")
Log.e("TAG","MessageReceived")
CoroutineScope(Dispatchers.IO).launch {
NotificationApp.db?.notificationDao()?.setNotification(Notification(data = p0.data["key_1"]))
}
showNotification(p0)
}
fun showNotification(data: RemoteMessage) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_input_get)
.setContentTitle(data.notification?.title)
.setContentText(data.notification?.body)
.setContentIntent(pendingIntent)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, "test_notification_channel_id", NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(channel)
}
manager.notify(0, notificationBuilder.build())
}
Манифест:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_launcher_background" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorPrimary" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/notification_main_chanel_id" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/notification_main_chanel_id" />
И пример уведомления в Почтальоне:
{
"data": {
"title": "I'd tell you a chemistry joke",
"message": "but I know I wouldn't get a reaction",
"image-url":
"https://docs.centroida.co/wp-content/uploads/2017/05/notification.png",
"key_1" : "Heh message"
},
"to": "DEVICE_TOKEN",
"priority": "high"
}