Android:导航深度链接在 handleDeeplink()

时间:2021-05-12 20:05:32

标签: android android-activity android-jetpack-navigation android-deep-link onnewintent

我已经使用 Jetpack Navigation 在我的应用中实现了深度链接。我的应用程序遵循单一活动架构。片段之间的导航由导航图组织。

我发现了一个案例,其中两者 onCreateonNewIntent 回调都被调用。这不应该发生。让我解释一下用例:

  1. 用户从应用重定向到浏览器。
  2. 当用户在浏览器中时,应用关闭(由操作系统或用户)
  3. 用户通过深层链接重定向回应用。

上面用例的 Logcat 看起来是这样的(按正确的顺序):

  • 2021-05-13 09:01:53.261 onPause MainActivity@336e6f1 //重定向到浏览器
  • 2021-05-13 09:02:21.584 onDestroy MainActivity@336e6f1 //应用被用户或操作系统关闭
  • 2021-05-13 09:02:24.804 onCreate MainActivity@4a820dd //重定向回应用
  • 2021-05-13 09:02:24.940 onNewIntent MainActivity@4a820dd
  • 2021-05-13 09:02:24.979 onCreate MainActivity@349ea37
  • 2021-05-13 09:02:25.102 onResume MainActivity@349ea37
  • 2021-05-13 09:02:25.495 onDestroy MainActivity@4a820dd

因此应用程序一次创建 MainActivity 的两个实例,并在同一个实例中触发 onCreateonNewIntent 回调。

当应用关闭而用户在浏览器中时,logcat 看起来像这样:

  • 2021-05-13 08:57:47.097 onPause MainActivity@7507cde
  • 2021-05-13 08:58:18.310 onNewIntent MainActivity@7507cde
  • 2021-05-13 08:58:18.312 onResume MainActivity@7507cde

singleTasksingleInstance 启动模式都没有改变任何东西。

我的问题是:

  1. 怎么可能同时调用 onCreateonNewIntent 回调?
  2. 为什么一次创建了两个 MainActivity 实例?
  3. 当用户从应用导航回来,然后通过最近的应用打开应用时,会触发与上述 logcat 中相同的日志。为什么会这样?

我会非常感谢回答我问题的人。在这里我添加我的代码:

清单:

<activity
    android:name=".main.MainActivity"
    android:launchMode="singleTop">

    <nav-graph android:value="@navigation/nav_graph" />

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

导航图:

<fragment
    android:id="@+id/paymentRedirectFragment"
    android:name="com.example.myapp.PaymentRedirectFragment">
    <action
        android:id="@+id/action_paymentRedirectFragment_to_transactionCompletionFragment"
        app:destination="@id/transactionCompletionFragment"
        app:popUpTo="@id/paymentRedirectFragment"
        app:popUpToInclusive="true" />
    <deepLink
        android:id="@+id/web_payment_deep_link"
        app:uri="com.example.myapp://foo/bar/this_is_just_example" />
</fragment>

主要活动:

private val navController by lazy {
    findNavController(R.id.mainNavigationFragment)
}

override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(R.style.AppTheme)
    super.onCreate(savedInstanceState)
    setSupportActionBar(toolbar)

    NavigationUI.setupWithNavController(
        binding.bottomNavigation,
        navController
    )
}

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

对浏览器的调用意图:

try {
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
} catch (ex: ActivityNotFoundException) {
    showSnackBar(R.string.browser_not_found, binding.root)
}

1 个答案:

答案 0 :(得分:0)

看起来这种行为是意料之中的。还有一个 issue 询问该行为是否有意。尚无答案。