Search code examples
androidmemory-leaksleakcanary

android.support.constraint.ConstraintLayout has leaked:


I'm using LeakCanary to detect memory leaks in an app. I successfully identified and fixed some leaks using it, but I am struggling find the root of this leak:

* android.support.constraint.ConstraintLayout has leaked:
* Toast$TN.mNextView
* ↳ LinearLayout.mContext
* ↳ HomeActivity.!(mDelegate)!
* ↳ AppCompatDelegateImplN.!(mActionBar)!
* ↳ ToolbarActionBar.!(mDecorToolbar)!
* ↳ ToolbarWidgetWrapper.!(mToolbar)!
* ↳ Toolbar.mParent
* ↳ ConstraintLayout
* Reference Key: 552b5bc5-409d-44c4-8412-87341237ae6d
* Device: samsung samsung SM-G960F starltexx
* Android Version: 8.0.0 API: 26 LeakCanary: 1.6.2 0ebc1fc
* Durations: watch=5769ms, gc=153ms, heap dump=933ms, analysis=5802ms

Is this leak caused by the Android SDK or app specific code?


Solution

  • The leak was caused by app specific code. One fragment called getActivity().setSupportActionBar() with a view contained in the fragments layout. When switching to another fragment the resources couldn't get gc'ed because the activity was still holding a reference to the no longer visible toolbar. I fixed this leak by calling getActivity().setSupportActionBar(null) in the fragments onDestroyView() method, which removes the reference to the toolbar.