简体   繁体   中英

Why android does not clean up memory after finishing activity?

In my case I have tow activities called A(Main Activity) and B (Child Activity). A will start B (B having some image loading stuff using Glide image library).

If I get the memory allocation using android memory monitor, I can clearly see the memory allocation grows.That is totally fine because we are doing some Image related things in activity B.Image Attached.

在此输入图像描述

So my problem is if I pressed back button in Activity B it will come to activity A and allocated memory will not be cleared.Memory allocation will still in same amount.

Is this normal android behaviour ?

If not how can I manually clean up memory ?

I manually run GC as follows but same result no luck :(.

In activity B

    @Override
    protected void onDestroy() {
       super.onDestroy();
       System.gc();
    }

1) OnDestroy is called when finish(); is called, simply pressing back button won't call this method, unless you program it to do so.

2) System.gc(); in onDestroy won't work, since your activity B is still active at onDestroy . You should call this from other Activity once the activity B is completely terminated.

3) Activity will remain on memory even onDestroy is called, if you leak your activities context to long lived object/thread/etc. (Memory leak)

Note: calling System.gc(); does not simply free your memory, it might not execute GC depending on the situation. See details here: Why is it bad practice to call System.gc()?

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