Opening custom chrome tab destroys the caller Activity in Android version prior to 12

387 Views Asked by At

I am using Android custom tabs for Authentication of my app. The custom tab is launched from the CustomTabLoginActivity. Once the user completes the sign up/login, the webpage gives a redirection with token and I register this URL in my intent filter to link back to the CustomTabLoginActivity.

<activity
            android:name="com.example.CustomTabLoginActivity"
            android:exported="true"
            android:launchMode="singleTop">

            <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="myapp" />
                <data android:host="@string/host_url_authentication" />
                <data android:pathPattern="/auth/callback.*" />
            </intent-filter>

        </activity>

This is how I call launch the Custom Tab

private fun openCustomTab(
        languageCode: String,
        authSession: String,
    ) {
        val loginUrl = "www.myappauth.com/someauthurl"
        val intent = CustomTabsIntent.Builder()
            .setColorScheme(CustomTabsIntent.COLOR_SCHEME_LIGHT)
            .build()
        intent.launchUrl(this, Uri.parse(loginUrl))
    }

I receive onNewIntent() callback on the CustomTabLoginActivity as desired.

However, on Android devices prior to version 12, Once the redirection happens, the existing instance of CustomTabLoginActivity is destroyed and a new instance is created. This breaks the functionality and the entire state is lost.

I expect the deeplink to trigger the onNewIntent() method as expected. Somehow it doesn't work in Android versions lesser than Android 12 instead it recreates the previous activity.

What did I try until now: I tried using FLAG_ACTIVITY_NEW_TASK for custom tab. This prevents the destruction of the previous activity, however, the custom tab now behaves as a normal browser instance and stays in the recent tasks as a separate app which pretty much destroys the whole concept of custom tabs. The custom tab should appear as an activity in my app task itself, no?

val intent = CustomTabsIntent.Builder()
            .setColorScheme(CustomTabsIntent.COLOR_SCHEME_LIGHT)
            .build().apply {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK )
            }
0

There are 0 best solutions below