Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Links navigation in Jetpack Compose

I want to use deep links with Jetpack Compose's Nav Host and followed this page on Compose Navigation: https://developer.android.com/jetpack/compose/navigation#deeplinks

My implementation: AndroidManifest.xml:

<application ...>
    <activity
    ...
    android:allowTaskReparenting="true"
    android:launchMode="singleInstance">
        ...
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" android:host="xkcd.com" />
            <data android:scheme="https" android:host="www.xkcd.com" />
        </intent-filter>
    </activity>
</application>

MainActivity.onCreate().setContent{}

val rootUri = "https://www.xkcd.com"
NavHost(navController = navController, startDestination = "mainView") {
    composable("mainView", deepLinks = listOf(navDeepLink { uriPattern = rootUri })) {
        MainContent()
    }
    composable(
        route = "singleView/{number}",
        arguments = listOf(navArgument("number") { type = NavType.IntType }),
        deepLinks = listOf(navDeepLink { uriPattern = "$rootUri/{number}" })
    ) { backStackEntry ->
        val number = backStackEntry.arguments?.getInt("number")
        SingleView(number)
    }
}

If I now click on a corresponding link the app opens but the navigation doesn't work

like image 746
Mr. Pine Avatar asked Mar 24 '26 17:03

Mr. Pine


2 Answers

The problem is with the Activity launchMode:

The documentation says that:

It is strongly recommended to always use the default launchMode of standard when using Navigation. When using standard launch mode, Navigation automatically handles deep links by calling handleDeepLink() to process any explicit or implicit deep links within the Intent. However, this does not happen automatically if the Activity is re-used when using an alternate launchMode such as singleTop. In this case, it is necessary to manually call handleDeepLink() in onNewIntent(), as shown in the following example:

override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    navController.handleDeepLink(intent)
}
like image 176
Neno Avatar answered Mar 26 '26 07:03

Neno


you also can do this

setContent {
        DisposableEffect(Unit) {
            val listener = Consumer<Intent> {
                //do som
            }
            addOnNewIntentListener(listener)
            onDispose { removeOnNewIntentListener(listener) }
        }
    }
like image 28
Eiffelyk Avatar answered Mar 26 '26 08:03

Eiffelyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!