Android Memory Leaks InputMethodManager Solved

Main Activity is not garbage collected even after finish because it is referenced by InputMethodManager indirectly .

Many times we see that when an android app is closed (means the last activity is finished ), we get that the main activity is not garbage collected as is is referenced by InputMethodManager indirectly , mainly this issue comes when we use RecyclerView in the fragment associated with FragmentStatePagerAdapter in that activity , TreeObserver or something related with InputMethodManager being used.

Even after onDestroy() of that main activity is being called the app keeps the reference of that activity as it is referenced by InputMethodManager indirectly.

So, we cannot fix it, as it’s due the bug in Android Source code

Link one

Link two

There can be some ways to fix it but we did not get the way to fix it . After some observations we realize that if any other activity is being called after that the finish of main activity the things is going perfect , no more Memory Leaks by InputMethodManager.

So we created the DummyActivity.java like this

https://gist.github.com/amitshekhariitbhu/6fe89df3e9fa73bb99d77542a2c96a88

And a theme in styles.xml and added that in Androidmanifest.xml


https://gist.github.com/amitshekhariitbhu/f74a9a58aac663a6b68921414d415c1ehttps://gist.github.com/amitshekhariitbhu/9133e499225e2ebbfa17ab213165b47e

And added the following code in MainActivity.java

https://gist.github.com/amitshekhariitbhu/4ae420fc35c60f503f0a863d882b98b2

In this way , Dummy activity is being called after the Main Activity but cannot be noticed as 500ms is too small and even the dummy activity is transparent , so no chance of any side-effect or being noticed.

LeakCanary (A powerful library for finding memory leaks) : The developers of LeakCanary has also mentioned to ignore this leaks (Link) as it’s a bug in android source code.

But this is the way that we found to fix the memory leak created by InputMethodManager in MainActivity.

Hope this helps. Please recommend it so that other developers get benefit till the google solve this issue.

Read about Fast Android Networking here.

 

Also, Let’s become friends on Twitter, Linkedin, Github, and Facebook.


Amit Shekhar

Amit Shekhar

Co-Founder at Mindorks | Learning is a journey, let’s learn together