Android service causes memory problems Android service causes memory problems sqlite sqlite

Android service causes memory problems


The core of your issue is that you don't know what content is still being referenced, and what's referencing it.

It should be straightforward to track down where memory is allocated with the tools inside Android Studio. Memory Profiling 101 walks through how to use memory monitor, allocation tracker and heap-viewer to find specific problems.

Really, these tools give you very clear insight into where your memory is going. I'd start there and snoop out what your second activity still has handles to.


First things first, turn on Strict mode to detect activity leaks by adding this to the OnCreate of your apps first activity:

StrictMode.SetVmPolicy (new StrictMode.VmPolicy.Builder ().DetectAll ().PenaltyLog ().Build ());  

This will dump out a warning into logcat every time more than 1 activity instance of a type is detected. It'll look like this:

[StrictMode] class md5962cfe7bc03e689322450e055e633b77.FirstActivity; instances=2; limit=1[StrictMode] android.os.StrictMode$InstanceCountViolation: class md5962cfe7bc03e689322450e055e633b77.FirstActivity; instances=2; limit=1[StrictMode]    at android.os.StrictMode.setClassInstanceLimit(StrictMode.java:1)

The next thing is to sever the peer object connection for your activity:

    protected override void OnDestroy ()    {        base.OnDestroy ();        base.Dispose ();        GC.Collect (GC.MaxGeneration);    }  

The base.Dispose () breaks the peer object connection between a C# object and a Java Vm object. http://developer.xamarin.com/guides/android/advanced_topics/garbage_collection/#Disposing_of_Peer_instances

In general, this should be enough fix the leaks for your sample. You can also go a step further and dispose then null all objects in the Activity that derive from Java.Lang.Object. For instance:

    protected override void OnDestroy ()    {        button.Dispose ();        button = null;        base.OnDestroy ();        base.Dispose ();        GC.Collect (GC.MaxGeneration);    }