0

我的应用程序包含几个片段,因为我在两个选项卡中显示它们。很少有片段被归类到第一个选项卡中,很少有片段进入另一个类别,显示为第二个选项卡。它还有许多将从网络上获取的图像。我正在使用延迟加载图像概念,没有对位图的 WeakReference 或 SoftReference。应用程序工作得很好,没有任何问题。但是如果我操作很长时间,它就会崩溃。我跟踪了堆更新并找到了以下内容。

当我访问新片段时,堆大小正在增加,当从堆栈中删除它们时,堆大小并没有减少。如果我访问旧片段,那么堆内存没有大量增加,但内存增加量仍然很小。为什么从堆栈中删除碎片时堆内存不回收内存。我正在跟踪所有片段的日志,每个片段 onDestroy() 都被称为仍然没有回收内存。内存的后续增加最终导致 OutOfMemoryError 说 Bitmap 超出 VM 预算错误并且 VM 无法分配 n 字节大小。

所有片段将有 3 种高质量的背景图像,它们存储在资源中。我在每个片段的 onDestroy() 中执行 unbindDrawables。对于位图图像的使用,我将内存限制为堆内存的第 5 部分。仍然OOME来了,所有的门都为我关闭,无法找到解决方案。

下面是我将用于片段导航的示例代码

FragmentManager fm = getFragmentManager();
            if(fm!=null)
            {
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.llfirst, fragments1);//if second tab ft.replace(R.id.llsecond,fragments2);
                ft.addToBackStack(null);
                ft.commit();
            }

最后,还有一个问题是应用程序中使用的片段数量是否有限制。

4

1 回答 1

0

我猜位图大小太大。它没有被正确释放,gc 无法回收内存。希望这可以帮助。

XML 布局

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/RootView"
 >

@Override
protected void onDestroy() {
super.onDestroy();

unbindDrawables(findViewById(R.id.RootView));
System.gc();
}

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));
        }
    ((ViewGroup) view).removeAllViews();
    }
}
于 2012-11-01T14:08:29.733 回答