Memory leak detected in Chrome Custom Tabs Memory leak detected in Chrome Custom Tabs google-chrome google-chrome

Memory leak detected in Chrome Custom Tabs


Found the Answer for this question -

If you are launching customTab as follow

private void launchChromeCustomTab(final Context context, final Uri uri) {     mServiceConnection = new CustomTabsServiceConnection() {        @Override        public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient client) {            client.warmup(0L);            final CustomTabsIntent intent = new CustomTabsIntent.Builder().build();            intent.launchUrl(context, uri);            mIsCustomTabsLaunched = true;        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };    CustomTabsClient.bindCustomTabsService(context, "com.android.chrome", mServiceConnection);}

Then you need to unbind this mServiceConnection onDestroy method as -

@Overrideprotected void onDestroy() {    super.onDestroy();    this.unbindService(mServiceConnection);    mServiceConnection = null;}

That will stop throwing

android.app.ServiceConnectionLeaked: Activity <Your_Activity> has leaked ServiceConnection 


The MainActivity in the sample creates an instance of CustomTabsServiceConnection and CustomTabsCallback as anonymous inner classes.

If you change them to be static inner classes, therefore removing the this reference to the MainActivity, and set the references to the MainActivity as WeakReferences, you will see that LeakCanary stops reporting about the MainActivity leaking.

Now, you may still see leak canary report about the ServiceConnection leaking if you set it to watch that object. The reason is that it is linked to the Chrome service and cannot be cleaned by GC until GC also runs on the server side.

I created a test that binds and unbinds the Service in a loop and I've confirmed that the ServiceConnections are indeed being collected after a while.

So, the Demo can be improved in order to avoid the ServiceConnection holding a reference to the MainActivity, avoiding having a heavy object like an Activity being alive a long time after the service is disconnected, and it's not a problem with the Custom Tabs library.