android – ViewPager,PagerAdapter和Bitmap导致内存泄漏(OutOfMemoryError)

前端之家收集整理的这篇文章主要介绍了android – ViewPager,PagerAdapter和Bitmap导致内存泄漏(OutOfMemoryError)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经构建了一个显示天气数据Android应用程序(如果你想测试问题,我可以私下给你一个应用程序名称).用户可以从一天浏览到另一天以查看特定日期的天气.

应用架构

我的应用程序使用片段(单个MainActivity和导航抽屉调用特定片段).

DayPagerFragment使用具有无限页数(动态片段)的ViewPager.页面代表一天.

DayPagerFragment

public class DayPagerFragment extends Fragment {

    private ViewPager mViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_day,container,false);
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view,savedInstanceState);

        mViewPager = (ViewPager) view.findViewById(R.id.pager);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(new DayAdapter(getChildFragmentManager()));
    }

    private static class DayAdapter extends FragmentStatePagerAdapter {

        public DayAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return DayFragment.newInstance(null);
        }

        @Override
        public int getCount() {
            // I don't know the number to put here becauseI don't have 
            // a defined number of fragments (= dynamic fragments)
            return 1; 
        }

        @Override
        public int getItemPosition(Object object){
            return DayAdapter.POSITION_NONE;
        }

    }

    public void setCurrentPagerItemPrev() {
        //mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
        mAdapterViewPager.getRegisteredFragment(mViewPager.getCurrentItem() - 1);
    }

    public void setCurrentPagerItemNext() {
        //mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
        mAdapterViewPager.getRegisteredFragment(mViewPager.getCurrentItem() + 1);
    }

}

第一个优化:使用FragmentStatePagerAdapter进行管理,因为FragmentPagerAdapter不适合我的使用/动态片段(将整个片段存储在内存中).

第二次验证:我已使用setOffscreenPageLimit(1)设置应保留在当前页面任一侧的页数.

DayFragment

public class DayFragment extends Fragment {

    private TextView mDay;
    private TextView mMonth;
    private Button mPrevDay;
    private Button mNextDay;
    private ImageView mCenter;
    private ImageView mLeft;
    private ImageView mRight;
    ...
    private DayRepository dayRepository;
    private Day currentDay;
    private Day prevDay;
    private Day nextDay;
    private DayUtil dayUtil;
    private DayUtil dayUtilPrev;
    private DayUtil dayUtilNext;
    private Calendar cal;
    private Calendar calPrev;
    private Calendar calNext;

    public static DayFragment newInstance(Calendar calendar) {
        DayFragment dayFragment = new DayFragment();

        Bundle args = new Bundle();
        args.putInt("year",calendar.get(Calendar.YEAR));
        args.putInt("month",calendar.get(Calendar.MONTH));
        args.putInt("day",calendar.get(Calendar.DAY_OF_MONTH));
        dayFragment.setArguments(args);

        return dayFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_day_nested,false);

        mDay = (TextView) view.findViewById(R.id.textView_day);
        mMonth = (TextView) view.findViewById(R.id.textView_month);
        mCenter = (ImageView) view.findViewById(R.id.imageView_center); // Weather symbol (sun,cloud...) of D-Day
        mLeft = (ImageView) view.findViewById(R.id.imageView_left); // Weather symbol of D-1
        mRight = (ImageView) view.findViewById(R.id.imageView_right);  // Weather symbol of D-2

        //... get 6 others TextView/ImageView

        MyApplication app = (MyApplication) getActivity().getApplicationContext();

        // Get bundle args
        int day = getArguments().getInt("day");
        int month = getArguments().getInt("month");
        int year = getArguments().getInt("year");

        // Date
        this.cal = new GregorianCalendar(year,month,day);

        // Get prev/next day (for nav arrows)
        this.calPrev = (GregorianCalendar) this.cal.clone();
        this.calPrev.add(Calendar.DAY_OF_YEAR,-1);
        this.calNext = (GregorianCalendar) this.cal.clone();
        this.calNext.add(Calendar.DAY_OF_YEAR,1);

        // Get data from database
        //...

        // Utils
        this.dayUtil = new DayUtil(currentDay,getActivity());
        this.dayUtilPrev = new DayUtil(this.prevDay,getActivity());
        this.dayUtilNext = new DayUtil(this.nextDay,getActivity());
        String dateCurrentDayName = FormatUtil.getDayName(app.getLocale()).format(this.cal.getTime());
        String dateCurrentDayNameCap = dateCurrentDayName.substring(0,1).toUpperCase() + dateCurrentDayName.substring(1);
        String dateCurrentMonthName = FormatUtil.getMonthName(month,app.getLocale());

        // Update UI
        //... lot of setText(...) using day object and utils
        mLeft.setImageResource(this.dayUtilPrev.getDrawable());
        mCenter.setImageResource(dayUtil.getDrawable());
        mRight.setImageResource(this.dayUtilNext.getDrawable());

        return view;
    }

    @Override
    public void onViewCreated(View view,savedInstanceState);

        // Custom fonts
        MyApplication app = (MyApplication) getActivity().getApplication();
        ViewGroup vg = (ViewGroup)getActivity().getWindow().getDecorView();
        ViewUtil.setTypeFace(app.getTrebuchet(),vg);

        // Navigation between days
        mMoonPrevDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ((MainActivity)getActivity()).viewDay(calPrev);
            }
        });
        mMoonNextDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((MainActivity) getActivity()).viewDay(calNext);
            }
        });
    }

    // Never called!
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w("com.example","Fragment day destroyed");
    }

}

问题:

我的应用程序非常图形化,因为每个页面显示

> 10 TextBox(内部文本根据日期而变化)
> 4 ImageView(D-1,D-Day,D 1的天气符号)另一个ImageView

当我浏览ViewPager页面时,我快速得到OutOfMemoryError(在/ – 30页之后).

这就像片段没有从内存中释放出来.垃圾收集器不像我预期的那样工作(我认为这是因为有些东西引用了旧片段).

logcat的

04-06 20:01:21.683  27008-27008/com.example D/dalvikvm﹕ GC_BEFORE_OOM freed 348K,2% free 194444K/196608K,paused 93ms,total 93ms
04-06 20:01:21.683  27008-27008/com.example E/dalvikvm-heap﹕ Out of memory on a 1790260-byte allocation.
04-06 20:01:21.693  27008-27008/com.example E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example,PID: 27008
    java.lang.OutOfMemoryError
            at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
            at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
            at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
            at android.content.res.Resources.loadDrawable(Resources.java:2110)
            at android.content.res.Resources.getDrawable(Resources.java:700)
            at android.widget.ImageView.resolveUri(ImageView.java:638)
            at android.widget.ImageView.setImageResource(ImageView.java:367)
            at com.example.ui.DayFragment.onCreateView(DayFragment.java:126) //...mLeft.setImageResource()
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
04-06 20:01:21.773  27008-27008/com.example I/dalvikvm-heap﹕ Clamp target GC heap from 197.480MB to 192.000MB
04-06 20:01:21.773  27008-27008/com.example D/dalvikvm﹕ GC_FOR_ALLOC freed 565K,2% free 193932K/196608K,paused 73ms,total 73ms

我有内存泄漏,但我不知道为什么和在哪里.
我使用过Eclipse MAT(Memory Analyzer),但我不知道在哪里看.

你能帮助我吗?

编辑:对于加载字体,我使用以下代码

DayFragment.java

// Custom fonts
MyApplication app = (MyApplication) getActivity().getApplication();
ViewGroup vg = (ViewGroup)getActivity().getWindow().getDecorView();
ViewUtil.setTypeFace(app.getTrebuchet(),vg);

MyApplication.java

public Typeface getTrebuchet() {
    if (trebuchet == null){
        trebuchet = Typeface.createFromAsset(getAssets(),Consts.PATH_TYPEFACE_TREBUCHET);
    }
    return trebuchet;
}

我的DDMS显示内存泄漏:

编辑2:重要!

我在我的应用程序中使用导航抽屉,由我唯一的活动MainActivity处理.导航抽屉使用片段(而不是活动).

这就是DayPagerFragment从Fragment(而不是FragmentActivity或Activity)扩展的原因.

要在天之间滑动,用户必须触摸两个按钮(上一个/下一个).我在DayFragment中的这些按钮上使用了setOnClickListener(请参阅我的更新代码).

问题是我调用((MainActivity)getActivity()).viewDay(calPrev);

主要活动

public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    private NavigationDrawerFragment mNavigationDrawerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Set up the navigation drawer
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
    }
    ...
    public void viewDay(Calendar calendar) {
        DayFragment dayFragment = DayFragment.newInstance(calendar); // The problem is here I think !
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out)
                .replace(R.id.container,dayFragment)
                .addToBackStack(null)
                .commit();
    }

}

所以…我认为,因为我每次都会实现一个新的片段,ViewPager无法完成他的工作!并且MainActivity对每个片段保持引用:这就是垃圾收集器不释放内存的原因.

现在:

>我不知道我的理论是否正确
>如何纠正?怎样,从setOnClickListener调用setCurrentPagerItemPrev和setCurrentPagerItemNext方法(参见我在DayPagerFragment中更新的代码)?

注意:我使用mAdapterViewPager.getRegisteredFragment()而不是mViewPager.setCurrentItem,因为我的DayAdapter从SmartFragmentStatePagerAdapter扩展,但它是相同的.

解决方法

你需要在这里检查两件事:图像和字体.

图像使用大量内存,因此您需要做一些工作才能快速释放它们.我已经使用以下代码来帮助清理我的内存,它删除了有助于更快地清理的引用.

此外,在短时间内加载许多高质量图像可能会导致错误,因为Android增加堆空间有点慢.请参阅我的答案:Android Understanding Heap Sizes.您可能需要在清单文件中设置android:largeHeap =“true”,但只能在优化图像和字体后执行此操作.

使用DDMS堆视图检查内存是否维护级别,这意味着您正在清理滚动页面.这需要在IDE上安装Android工具插件.

public abstract class SimplePagerAdapter extends PagerAdapter {
// ...
@Override
public void destroyItem(ViewGroup container,int position,Object object) {
    container.removeView((View) object);
    unbindDrawables((View) object);
    object = null;
}
protected 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();
    }
}
}

然后,检查你获得字体的方式.确保缓存对Typeface.createFromAsset(…)的所有调用,如下例所示:

public Typeface getFont(String font,Context context) {
    Typeface typeface = fontMap.get(font);
    if (typeface == null) {
        typeface = Typeface.createFromAsset(context.getResources().getAssets(),"fonts/" + font);
        fontMap.put(font,typeface);
    }
    return typeface;
}

编辑:问题更新后的额外信息

更改适配器以使用对象列表:

在getCount()上返回该列表的大小,

将对象添加到列表调用时:

notifyDataSetChanged();
mPagerContainer.invalidate();

然后,当您接近当前列表的末尾时,请求更多项目并将它们添加到列表中,再次调用上面的代码.

我已经实现了类似的东西,这是一个无限的寻呼机,有大量的高分辨率图片,但是,我没有使用片段,所以我不完全知道如何从列表中删除它们.

我可以看到你没有覆盖isViewFromObject,也许你想在你的寻呼机适配器中添加以下方法

@Override
public boolean isViewFromObject(View view,Object object) {
    View _view = (View) object;
    return view == _view;
}
原文链接:/android/309653.html

猜你在找的Android相关文章