应用架构
我的应用程序使用片段(单个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 93ms04-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.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.000MB04-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 FontsMyApplication 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扩展,但它是相同的.
@H_502_76@解决方法 你需要在这里检查两件事:图像和字体.图像使用大量内存,因此您需要做一些工作才能快速释放它们.我已经使用以下代码来帮助清理我的内存,它删除了有助于更快地清理的引用.
此外,在短时间内加载许多高质量图像可能会导致错误,因为AndroID增加堆空间有点慢.请参阅我的答案:Android Understanding Heap Sizes.您可能需要在清单文件中设置androID:largeHeap =“true”,但只能在优化图像和字体后执行此 *** 作.
使用DDMS堆视图检查内存是否维护级别,这意味着您正在清理滚动页面.这需要在IDE上安装AndroID工具插件.
public abstract class SimplePagerAdapter extends PagerAdapter {// ...@OverrIDepublic 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,也许你想在你的寻呼机适配器中添加以下方法:
@OverrIDepublic boolean isVIEwFromObject(VIEw vIEw,Object object) { VIEw _vIEw = (VIEw) object; return vIEw == _vIEw;}总结
以上是内存溢出为你收集整理的android – ViewPager,PagerAdapter和Bitmap导致内存泄漏(OutOfMemoryError)全部内容,希望文章能够帮你解决android – ViewPager,PagerAdapter和Bitmap导致内存泄漏(OutOfMemoryError)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)