繁体   English   中英

Jetpack Compose 中的深层链接导航

[英]Deep Links navigation in Jetpack Compose

我想使用 Jetpack Compose 的 Nav Host 的深层链接,并在 Compose Navigation 上关注此页面: https://developer.android.com/jetpack/compose/navigation#deeplinks

我的实现: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)
    }
}

如果我现在单击相应的链接,应用程序会打开,但导航不起作用

问题在于 Activity launchMode

文档说强烈建议在使用导航时始终使用standard的默认launchMode 使用标准启动模式时,Navigation 通过调用handleDeepLink()自动处理深层链接,以处理 Intent 中的任何显式或隐式深层链接。 但是,如果在使用诸如launchMode类的备用启动模式时重新使用 Activity,这不会自动singleTop 在这种情况下,需要在onNewIntent()中手动调用handleDeepLink() ,如下例所示:

override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    navController.handleDeepLink(intent)
}

我通过删除它来工作

android:launchMode="singleInstance"

从清单

对于 Kamil,您可以将 navController 保存到 viewModel,然后在 onNewIntent 方法中重用它。

class HomeActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val model: MainModel by viewModels()

    setContent {
      val navController = rememberNavController()
      model.navController = navController

      MyTheme {
        Scaffold {
          NavigationComponent(navController)
        }
      }
    }
  }

  override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    val model: MainModel by viewModels()

    model.navController.handleDeepLink(intent)
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM