Free fragment memory

1.5k views Asked by At

I need to optimize memory in my application. When fragment is closed I need to free-up memory used by that fragment.

I am doing following steps to free-up memory

@Override
public void onDestroy() {
    super.onDestroy();
    txt_legal_1 = null;
    txt_legal_2 = null;
    progressBar = null;
    mHandler = null;
    prefs = null;
    content = null;
    System.runFinalization();
    Runtime.getRuntime().gc();
    System.gc();
}

But still memory is not free-up.Can any-one help on this ?

3

There are 3 answers

0
 Ekalips On

Look at your Activity code, I bet that something is referencing Fragment, or one of it's field. Java Garbage Cleaner can't cleanup object from memory if at least one link persists (it can be even some listener, receiver or so on)

Also you can't expect, that running System.gc() will clean up memory, in fact you just hinting system to perform cleanup. You can look if GC will be completed successfully in "Monitor" tab in Android Studio. There is a button "Initiate GC", with it GC will really start. And if you see that memory consumption will not change, that will mean that you did something wrong, and something still keeps Fragment(or it field) link.

0
Manza On

Consider using Leak Canary.

It helps to detect and fix memory leaks.

0
rafsanahmad007 On

try this: in your fragment

@Override
public void onDestroy() {
    super.onDestroy();
    removeListeners(); //remove any listener..
    try {
        getActivity().unregisterReceiver(receiver); //unregister any receiver that you register in fragment
        unbindDrawables(rootView.findViewById(R.id.coordinator));  //R.id.coordinator is the root layout of your fragment view
        System.gc();
    } catch (Exception e) {

    }
}


//free up any drawables..views
private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        if (!(view instanceof AdapterView<?>))
            ((ViewGroup) view).removeAllViews();
    }
}