Android Fragment内存泄漏

时间:2015-05-29 14:38:43

标签: android android-fragments memory memory-leaks out-of-memory

我的应用程序中存在内存泄漏问题。 我在第一个中用2个片段测试它我在第一个中创建一个大变量(ArrayList arr = new ArrayList(10000000);)以便查看更改片段时内存是否为空(第二个为空),但不幸的是,这不会发生。

Activity是一个ActionBarActivity,当我更改片段时,我会删除(片段)和popbackstack,但每次更改时内存都会增加。

请帮帮我!!!!

下面我发布一些代码:Activity是ActionBarActivity,它有一个侧边菜单NavigationDrawer:

public class MainActivity extends ActionBarActivity implements NavigationDrawerCallbacks {
   private Toolbar mToolbar;
   private NavigationDrawerFragment mNavigationDrawerFragment;
   private DrawerLayout mDrawerLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
       mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
       setSupportActionBar(mToolbar);
       mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
       mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
       setActionBarMenu(true);
       selectItem(1);
    }

    private void selectItem(int position) {
        final FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
           ft.remove(fm.findFragmentByTag(fm.getFragments().get(fm.getBackStackEntryCount() - 1).getTag()));
           fm.popBackStack();
        }
        switch (position) {
            case 0:
                break;
            case 1:
                onChangeFragment(new UsersCheckInFragment(), false);
            case 2:
            etc...
        }

        ft.commit();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        selectItem(position);
    }

    public void onChangeFragment(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, ((Object) fragment).getClass().getSimpleName());
        if (addToBackStack)
            ft.addToBackStack("");
       ft.commit();
    }
}

片段:

public class UsersFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_users, container, false);
        mainActivity = (MainActivity) getActivity();
        ArrayList<Integer> arr = new ArrayList<Integer>(10000000);
        return view;
    }
}

这里有一些内存屏幕

first fragment

second fragment

again first fragment

1 个答案:

答案 0 :(得分:1)

这不是内存泄漏,最终系统会调用垃圾收集器。完成后,系统不需要立即从内存中删除碎片。