首页 > 解决方案 > 活动的 onCreate 方法始终使用启动模式“singleTask”调用

问题描述

我在我的应用程序中使用Branch IO,根据他们的文档,我正在使用android:launchMode="singleTask"我的活动。

这是我的 AndroidManifest 的一些代码片段。

        <activity
        android:name=".SplashScreen"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateAlwaysHidden|adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <data
                android:host="open"
                android:scheme="com.package.name" />

            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

        <!-- Branch App Links (optional) -->
        <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="app.link"
                android:scheme="https" />
            <!-- <data android:scheme="https" android:host="example-alternate.app.link" /> -->
        </intent-filter>
    </activity>

一切正常,除了当我在使用应用程序时按下主页按钮并点击应用程序/启动器图标时,会调用启动屏幕活动的 onCreate 方法,这使得它看起来像是从一开始就启动了应用程序。但是,如果我在使用应用程序时按下主页按钮并从最近的应用程序中打开它,则不会调用 onCreate 并且一切正常。

从最近的应用程序和应用程序/启动器图标带到前台时,如何使应用程序行为保持一致?

我尝试删除使应用程序/启动器图标和最近的应用程序完美启动的 singleTask 启动模式,但是当点击分支 IO 链接时,会创建应用程序的新实例。我可以理解,要克服这个问题,只有他们要求将 singleTask 置于启动模式。

我已经在许多使用深层链接的应用程序中检查了这种情况,但它们没有这个问题!

我一定做错了我看不到的事情。

是否缺少某些东西或实施有误?

标签: androidandroid-activitydeep-linkingbranch.ioandroid-deep-link

解决方案


这个问题的解决方案是转向单一活动架构。由于splash Activity是singleTask,每次从启动器图标将应用程序带到前台时,都会调用它的onStart方法。必须在 onStart 方法中编写路由逻辑,当从这里启动另一个活动时,应用程序状态将丢失。如果存在单个活动,则不会存在此问题。然而,人们将不得不处理令人讨厌的片段 backstacks。这不是一个简单但正确的方法。

为了快速解决问题,可以在活动的 onCreate 方法中使用此代码,并将 launchmode 设置为 singleTask。

        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
           return;
        }

这可能有助于避免不必要地执行 onCreate 中编写的代码。但是,这是推荐的解决方案,因为它不能解决问题的根本原因。


推荐阅读