Я работаю над многоплатформенным приложением на Kotlin со специфичным для Android кодом для обработки уведомлений и глубоких ссылок. Приложение использует NotificationService для получения push-уведомлений, которые должны направлять пользователей к определенным экранам исследования на основе ResearchPath, указанного в данных уведомления.
Проблема:
Когда приложение работает (на переднем или фоновом режиме), PendingIntent в уведомлении правильно переходит на целевой экран исследования. Однако, когда приложение закрыто, нажатие на уведомление открывает приложение на главном экране, а не переходит непосредственно на нужную страницу исследования.
Контекст кода:< /p>
- NotificationService.kt
Этот сервис обрабатывает входящие уведомления, настраивает канал уведомлений, создает уведомление и создает PendingIntent на основе ResearchPath в данных сообщения.Код: Выделить всё
class NotificationService : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { super.onMessageReceived(message) Log.i(TAG, "onMessageReceived: Message Received") createNotice(message) } private fun createNotice(message: RemoteMessage) { val getChannel = if (message.from?.contains("/topics/") == true) { if (message.from?.extractTopic() == Topics.ResearchPosted.name) ResearchNotification().notificationChannelId else FacultyNotification().notificationChannelId } else MessageNotification().notificationChannelId val builder = NotificationCompat.Builder(this, getChannel) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(message.notification?.title ?: "") .setContentText(message.notification?.body ?: "").setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) val key = message.data["created"]?.toLong()?.convertToInt() ?: Random.nextInt() val researchPath = message.data["key"] ?: "no_research" val pendingIntent = providePendingIntentNotice(researchPath) builder.setContentIntent(pendingIntent) val managerCompat = NotificationManagerCompat.from(this) if (ActivityCompat.checkSelfPermission( this, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { return } managerCompat.notify(key, builder.build()) } private fun providePendingIntentNotice(path: String): PendingIntent? { val deepLinkIntent = Intent( Intent.ACTION_VIEW, DeepLink.OpenResearch(researchPath = path).route.toUri(), this, MainActivity::class.java ) val deepLinkPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run { addNextIntentWithParentStack(deepLinkIntent) getPendingIntent(0, getPendingIntentFlag()) } return deepLinkPendingIntent } private fun getPendingIntentFlag() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT private fun String.extractTopic() = this.replace("/topics/", "") } - MainScreenGraph.kt
Этот код определяет граф навигации и настраивает глубокие ссылки для обработки параметра ResearchPath.Код: Выделить всё
fun NavGraphBuilder.mainScreenGraph(navController: NavController) { navigation( startDestination = MainScreenScreenRoutes.HomeScreen.route, route = ResearchHubNavigation.MainScreen.route ) { fadeThroughComposable( route = MainScreenScreenRoutes.HomeScreen.route, arguments = listOf(navArgument("researchPath") { nullable = true defaultValue = null type = NavType.StringType }), deepLinks = listOf(navDeepLink { uriPattern = DeepLink.OpenResearch().route action = "android.intent.action.VIEW" }) ) { val researchPath = it.arguments?.getString("researchPath") MainScreen( navHostController = navController, researchPath = researchPath ) } } } - DeepLink.kt
Этот файл содержит структуру для глубоких ссылок с OpenResearch настроен для обработки ResearchPath.Код: Выделить всё
sealed class DeepLink(val route: String) { data class OpenResearch(val researchPath: String = "{researchPath}") : DeepLink("$BaseDeepLinkUrl/research/${researchPath}") }
При нажатии на уведомление , приложение должно открыться на определенном экране исследования на основе ResearchPath, независимо от того, открыто ли приложение или закрыто.
Вопрос:
Как изменить эту настройку, чтобы PendingIntent правильно открывал экран сведений об исследовании, даже когда приложение полностью закрыто? Мы будем очень признательны за любые идеи или предложения по обработке глубоких ссылок в многоплатформенной среде Kotlin.
Подробнее здесь: https://stackoverflow.com/questions/791 ... -is-closed