Backstack and memory leakage

2019-06-25 23:04发布

I have developed a small API for dialog fragments based on Google support library with very simple requirements:

  • API could add (or replace) a modal dialog
  • API could dismiss dialog programmatically or user can dismiss dialog by pressing button

Does my API creates a memory leakage by constantly adding fragments to backstack?

public class DialogFragmentUtils {

private static final String DIALOG_TAG = "dialogTag";

public static void showDialogFragment(@Nullable Activity activity, @NotNull Fragment fragment) {
    if (activity instanceof FragmentActivity) {
        FragmentActivity fragmentActivity = (FragmentActivity) activity;
        FragmentManager fm = fragmentActivity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag(DIALOG_TAG);
        if (prev != null && prev.isAdded()) {
            ft.remove(prev);
        }
        ft.add(fragment, DIALOG_TAG);
        ft.addToBackStack(null);
        ft.commit();
    }
}

public static void dismissDialogFragment(@Nullable Activity activity) {
    if (activity instanceof FragmentActivity) {
        FragmentActivity fragmentActivity = (FragmentActivity) activity;
        FragmentManager fm = fragmentActivity.getSupportFragmentManager();
        DialogFragment dialog = (DialogFragment) fm.findFragmentByTag(DIALOG_TAG);
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
}

2条回答
劫难
2楼-- · 2019-06-25 23:40

Yes, its prone to low memory, not memory leak though. All back stack Fragment are kept in memory with hard references. So if you are keeping a ridiculous amount of Fragments in back stack then you will get out of memory.

Have a look here: When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?

UPDATE: I see your DIALOG_TAG is not changing so you are keeping only one Fragment in backstack at a time, because you remove old one if it exists. In this case you might not have the issue of low memory.

查看更多
可以哭但决不认输i
3楼-- · 2019-06-25 23:59

I believe it wont leak but to be sure you need to test it. As talkol said, you should use Eclipse MAT to analyse this issue. There is a good guide by vogel here and a good guide on the Android blog here. Create and close a bunch of dialogs and see if it makes a difference.

On a side note why do you use ft.close() instead of prev.dismiss() in your showDialogFragment() method. The correct way of closing dialogs is dismiss().

查看更多
登录 后发表回答