javaandroidmobile-applicationchrome-custom-tabsandroid-customtabs

Is there an approach to reuse the same Chrome custom tab that holds the same URL?


I am using the following lib: androidx.browser:browser:1.5.0

I tried using a CustomTabsSession and adding it to the CustomTabsIntent, so that each time I launch the URL, I will check if the session is null or not. If so, I will reuse the previously created custom tab. But unfortunately, it didn't work! Check my code below (when the button that's supposed to launch the URL is clicked, the below method is called):

NOTE: My MainActivity in the manifest is marked as singleInstance.

private void initCustomTabs() {
    if (customTabsSession == null) {
        customTabsServiceConnection = new CustomTabsServiceConnection() {
            @Override
            public void onCustomTabsServiceConnected(@NonNull ComponentName name, @NonNull CustomTabsClient client) {
                customTabsClient = client;
                customTabsSession = customTabsClient.newSession(null);
                launchCustomTab(myURL);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                customTabsClient = null;
                customTabsSession = null;
            }
        };
        CustomTabsClient.bindCustomTabsService(MainActivity.this, "com.android.chrome", customTabsServiceConnection);
    } else {
        launchCustomTab(myURL);
    }
}

private void launchCustomTab(String url) {
    CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    builder.setSession(customTabsSession);
    CustomTabsIntent customTabsIntent = builder.build();
    customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
}

Solution

  • Don't create a new session on every connect, but only once and furthermore (when knowing the CustomTabsSessionToken sessionToken) use method postMessage(). The method's signature shows, how it is supposed to be used:

    @CustomTabsService.Result
    protected abstract int postMessage(
        @NonNull CustomTabsSessionToken sessionToken,
        @NonNull String message,
        @Nullable Bundle extras
    )
    

    While your code does not seem to consider any CustomTabsSessionToken, which can be obtained with method getSessionTokenFromIntent(). Not to confuse with CustomTabsSession. Basically, the Custom Tabs Activity can be controlled with a session token. WebView would be the same instance of Activity and indeed easier to load this or that URL, without having to worry about opening too many Intent.FLAG_ACTIVITY_SINGLE_TOP, as you have it there.