0

Suppose that my app handles all example.com deep links, but the NavHost within MainActivity handles only example.com, example.com/account, and example.com/account/detail, while other paths are forwarded to another activity called WebViewActivity. How to create a fallback destination that will forward to another activity?

NavHost(navController = navController, startDestination = "root") {
  composable(
    "root",
    deepLinks = listOf(
      navDeepLink { uriPattern = "example.com" }
    ),
  ) {
  }
  composable(
    "account",
    deepLinks = listOf(
      navDeepLink { uriPattern = "example.com/account" }
    ),
  ) {
  }
  composable(
    "accountdetail",
    deepLinks = listOf(
      navDeepLink { uriPattern = "example.com/account/detail" }
    ),
  ) {
  }
  other("fallback") { // How?
  }
}

What I've tried so far:

  1. Using example.com/.* pattern: it takes precedence over accountdetail destination.

    composable(
      "fallback",
      deepLinks = listOf(
        navDeepLink { uriPattern = "example.com/.*" }
      ),
    ) {
      val url = it.arguments?.getParcelable<Intent>(NavController.KEY_DEEP_LINK_INTENT)
        ?.dataString
    }
    
  2. Catching in home destination and taking the URL from Activity.intent: too hacky.

fikr4n
  • 3,250
  • 1
  • 25
  • 46

1 Answers1

0

Well, in the end, instead of creating a fallback route, I do a simple hack.

NavHost(...) { ... }

LaunchedEffect(Unit) {
    // startingDeepLink is from Activity.intent?.data
    if (startingDeepLink?.let { navController.graph.hasDeepLink(it) } == false) {
        val shouldFinish = navController.popBackStack()
        if (shouldFinish) {
            // Finish the activity.
        }
        // Handle startingDeepLink here.
        // ...
    }
}
fikr4n
  • 3,250
  • 1
  • 25
  • 46