Я создаю приложение для обмена сообщениями, и мне нужно показывать хедз-ап уведомления на Android 7 и старше до Android 5.
Я создал FirebaseMessagingService вместе с NotificationChannel для отображения уведомлений для Android 8 и выше иэто хорошо работает с хедз-ап уведомлениями.На Android 7 FirebaseMessagingService метод onMessageReceived не работает, когда приложение находится в фоновом режиме.Поэтому я решил использовать BroadcastReceiver для отображения уведомлений в виде головы, и теперь это уведомление отображается на Android 7 в течение нескольких секунд, а затем оно остается в ящике вместе с обычным уведомлением.Я даже закомментировал FirebaseMessagingService, но все равно получаю обычное уведомление вместе с уведомлением хедз-ап.У меня есть ощущение, что есть другой способ реализации этого.
снимок экрана с тем, как выглядит уведомление сейчас
Вот мой код:
Файл MyFirebaseMessagingService:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// if (remoteMessage.notification !=null) {
// showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
// }
}
fun showNotification(title: String?, body: String?, context: Context) {
val intent = Intent(context, SearchActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(context, "my_channel_id_01").apply {
setSmallIcon(R.drawable.my_friends_room_logo)
setContentTitle(title)
setContentText(body)
setSound(soundUri)
setDefaults(DEFAULT_ALL)
setTimeoutAfter(2000)
setPriority(PRIORITY_HIGH)
setVibrate(LongArray(0))
}
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
ВызовshowNotification () из файла FirebaseBackgroundService:
class FirebaseBackgroundService : BroadcastReceiver() {
var myFirebaseMessagingService = MyFirebaseMessagingService()
var notificationtitle: Any? = ""
var notificationbody: Any? = ""
override fun onReceive(context: Context, intent: Intent) {
if (intent.extras != null) {
for (key in intent.extras!!.keySet()) {
val value = intent.extras!!.get(key)
Log.e("FirebaseDataReceiver", "Key: $key Value: $value")
if (key.equals("gcm.notification.title", ignoreCase = true) && value != null) {
notificationtitle = value
}
if (key.equals("gcm.notification.body", ignoreCase = true) && value != null) {
notificationbody = value
}
}
myFirebaseMessagingService.showNotification(notificationtitle as String, notificationbody as String, context)
}
}
}
Мой JSON выглядит так:
{
"to" : "some-id",
"priority":"high",
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification",
"content_available" : true,
"sound": "sound1.mp3",
"click_action" : "chat"
},
"data": {
"uid" : "yOMX4OagvgXEl4w4l78F7SlqzKr2",
"method" : "chat",
"android_channel_id": "1"
}
}