简体   繁体   中英

How does the Android Studio initiates the Garbage Collector and how does it work?

I am having a hard time trying to find a possible Memory leak. I've got an Activity which is doing some heavy work in the Background.

After some tasks, the app consumes too much memory. It seems that it does not get cleaned up properly.

This is the Activity in the default state:

在此输入图像描述

If I run the task which the Activity is doing, more and more memory is allocated.

Activity after some work: 在此输入图像描述

At first I thought this must be a Memory Issue, cause the GC can't properly free up the memory. As far as I know, the GC can free the memory, if there are no reference left to the Objects. Is that correct?

Now comes the part which confuses me:

If I run the GC from Android Studio, the memory is cleaned up properly and my Activity never gets closed. I just have to use the Android Studio GC when to much memory is allocated. 在此输入图像描述

This is the one I mean:

在此输入图像描述

In general the question is:

Why can the Android Studio GC clean up the memory properly and why doesn't it work properly with the automatic android GC?

I know this is a pretty general question. I just want to know, if there are different types of garbage collections or something like that.

Also calling System.gc(); doesn't clean up the memory properly.

Additional Info:

Moto G 2nd gen

Android 5.0.2.

Memory leaks can happen because of several reasons. One common reason are bitmaps which are not recycled correctly. Other seed of memory leaks is keeping the context in objects. For example you launch an async task and pass a context because you need it later. While the async task is running it keeps a reference to the context and so the whole activity is in memory. This is also very frequent with anonymous and inner classes which have a reference to the parent class which usually is a fragment or and activity.

I suggest you to use the library leak canary to spot memory leaks and use the Android tools to track the allocations in order to discover exactly where the memory leak is happening.

Perhaps you can try to explicitly call System.gc(); somewhere periodically in your heavy processing code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM