免费碎片记忆

时间:2017-01-02 17:17:41

标签: android performance android-fragments memory-management java-memory-model

我需要在我的应用程序中优化内存。当片段关闭时,我需要释放该片段使用的内存。

我正在执行以下步骤来释放内存

@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();
}

但是记忆还没有释放。对此有任何帮助吗?

3 个答案:

答案 0 :(得分:0)

查看您的活动代码,我打赌某些内容正在引用Fragment或其中一个字段。如果至少有一个链接持续存在,Java Garbage Cleaner无法从内存中清除对象(它甚至可能是某些侦听器,接收器等)

另外你不能指望,运行System.gc()会清理内存,实际上你只是暗示系统执行清理。您可以在Android Studio的“监视器”选项卡中查看GC是否成功完成。有一个按钮“Initiate GC”,GC将真正开始。如果你发现内存消耗不会改变,那就意味着你做错了什么,还有一些东西仍然保持Fragment(或它的字段)链接。

答案 1 :(得分:0)

考虑使用Leak Canary

它有助于检测和修复内存泄漏。

答案 2 :(得分:0)

试试这个:在你的片段中

@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();
    }
}