0

我已经使用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

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

我的问题是:

  1. 怎么可能同时调用onCreate和回调?onNewIntent
  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)
}
4

1 回答 1

0

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

于 2021-05-30T12:29:02.573 回答