Я работаю над приложением для Android, в котором пользователи получают уведомления Firebase о новых сообщениях. Когда пользователь нажимает на уведомление, приложение должно перейти к определенному фрагменту (MessagesFragment) с помощью компонента навигации. Это прекрасно работает, когда приложение открыто, но если приложение закрыто, нажатие на уведомление открывает действие Launcher, которое представляет собой SplashActivity, без перехода к нужному фрагменту.
Код для MyFirebaseMessagingService
Ниже приведен код моей службы FirebaseMessagingService, в которой я создаю уведомление и указываю место назначения в NavDeepLinkBuilder:
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
class MyFirebaseMessagingService : FirebaseMessagingService() {
companion object {
const val NOTIFICATION_CHANNEL_NAME = "default_notification_channel"
const val NOTIFICATION_CHANNEL_ID = "channel_id"
var NOTIFICATION_ID = 0
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createNotificationChannel()
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
getNotificationWithDataPayload(remoteMessage)
}
}
private fun getNotificationWithDataPayload(message: RemoteMessage) {
val type = message.data["notificationType"]
val title = message.data["title"]
val body = message.data["body"]
val destinationId = when (type) {
"chat" -> R.id.messagesFragment
else -> R.id.mainFragment
}
val intentBundles = bundleOf(Constants.INTENT_ID to (message.data["typeId"]?.toInt() ?: 0))
val pendingIntent = createPendingIntentOrder(intentBundles, destinationId)
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
NOTIFICATION_ID += 1
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
private fun createPendingIntentOrder(arguments: Bundle?, destination: Int): PendingIntent {
return NavDeepLinkBuilder(applicationContext)
.setComponentName(MainActivity::class.java)
.setGraph(R.navigation.main_nav_graph)
.setDestination(destination)
.setArguments(arguments)
.createPendingIntent()
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... hen-app-is
Уведомление Android Firebase не переходит к определенному фрагменту, когда приложение закрыто ⇐ Android
Форум для тех, кто программирует под Android
1730499176
Anonymous
Я работаю над приложением для Android, в котором пользователи получают уведомления Firebase о новых сообщениях. Когда пользователь нажимает на уведомление, приложение должно перейти к определенному фрагменту (MessagesFragment) с помощью компонента навигации. Это прекрасно работает, когда приложение открыто, но если приложение закрыто, нажатие на уведомление открывает действие Launcher, которое представляет собой SplashActivity, без перехода к нужному фрагменту.
Код для MyFirebaseMessagingService
Ниже приведен код моей службы FirebaseMessagingService, в которой я создаю уведомление и указываю место назначения в NavDeepLinkBuilder:
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
class MyFirebaseMessagingService : FirebaseMessagingService() {
companion object {
const val NOTIFICATION_CHANNEL_NAME = "default_notification_channel"
const val NOTIFICATION_CHANNEL_ID = "channel_id"
var NOTIFICATION_ID = 0
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createNotificationChannel()
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
getNotificationWithDataPayload(remoteMessage)
}
}
private fun getNotificationWithDataPayload(message: RemoteMessage) {
val type = message.data["notificationType"]
val title = message.data["title"]
val body = message.data["body"]
val destinationId = when (type) {
"chat" -> R.id.messagesFragment
else -> R.id.mainFragment
}
val intentBundles = bundleOf(Constants.INTENT_ID to (message.data["typeId"]?.toInt() ?: 0))
val pendingIntent = createPendingIntentOrder(intentBundles, destinationId)
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
NOTIFICATION_ID += 1
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
private fun createPendingIntentOrder(arguments: Bundle?, destination: Int): PendingIntent {
return NavDeepLinkBuilder(applicationContext)
.setComponentName(MainActivity::class.java)
.setGraph(R.navigation.main_nav_graph)
.setDestination(destination)
.setArguments(arguments)
.createPendingIntent()
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79149544/android-firebase-notification-does-not-navigate-to-specific-fragment-when-app-is[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия