简体   繁体   中英

When Activity is destroyed on background,how to remove fragment

When my app switches to background,the system memory is low, then android will destroy my activity.At that time,I want to remove the fragments attached to activity,so that when activity switches to foreground,I can avoid any abnormal behavior of that activity.I do it like this:

@Override
    public void onSaveInstanceState(Bundle outState) {
        FragmentManager fm = getSupportFragmentManager();
        AbstractBaseViewFragment previous = (AbstractBaseViewFragment) fm.findFragmentByTag(FRAGMENT_TAG);
        if (previous != null) {
            fm.beginTransaction().remove(previous).commitAllowingStateLoss();
            fm.executePendingTransactions();
        }
        super.onSaveInstanceState(outState);
    }

so I want to ask:Are there any other good ideas to finish this target?Will my method cause any crashes?

You can try this: ft.detach(previous);

if (previous != null) {
                FragmentTransaction ft = fm.beginTransaction();
                ft.detach(previous);
                ft.remove(previous);
                ft.commitAllowingStateLoss();
... // the rest of your 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