Android的OutOfMemory解决

安卓开发中应注意内存的释放,一旦加载图片或其他占用太多内存,此时就会发生OOM错误,即内存泄露。

在开发中,尤其应注意图片资源的释放。
1。背景图片和ImageView释放------尤其注意图片资源
如:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.               android:orientation="vertical"
  4.               android:background="@drawable/main_background"
  5.               android:id="@+id/mian_bg"
  6.               android:scaleType="fitXY"
  7.               android:gravity="center"
  8.               android:layout_width="fill_parent"
  9.               android:layout_height="fill_parent"
  10.         >
  11.    <ImageView
  12.             android:layout_gravity="center"
  13.             android:src="@drawable/img_main_roll0"
  14.             android:id="@+id/main_cion"
  15.             android:layout_width="180dp"
  16.             android:layout_height="180dp"/>
  17.       
  18. </<LinearLayout>
  19. 先获取图片控件:
  20. public ImageView imageView;
  21. public LinearLayout linearLayout;
  22. imageView=(ImageView)findViewById(R.id.main_cion);
  23. linearLayout=(LinearLayout)findViewById(R.id.mian_bg);
  24. 应在次Activity销毁时释放
  25. protected void onDestroy() {
  26.         super.onDestroy();
  27.         imageView.setImageBitmap(null);//释放
  28.         linearLayout.setBackground(null);
  29.         System.gc();//通知进行回收
  30.     }
  31. 使用Bitmap记得不用时调用回收
  32. bitmap.recycle();
  33. 总结:
  34. 无论你是在xml中布局使用了:
  35. android:background   ,
  36. 还是在java代码中调用了:
  37. setBackground( background );-------API16+
  38. setBackgroundDrawable( background)--------API16-
  39. setBackgroundResource( resid)
  40. 的方式去设置了背景图片.
  41. 使用的时候,请调用一下对应的方法: 
  42. setBackgroundResource和 android:background → setBackgroundResource(0);
  43. setBackgroundDrawable( background) → setBackgroundDrawable (null)
  44. setBackground ( background ) → setBackground ( null )  
  45. 然后再onDestory中调用System.gc();
复制代码
2.确定不用的List,数组等参数
释放:Obj=null即可,list先clear(),在令其等于null;如内存紧张,可及时调用Syetem.gc()通知进行回收
posted @ 2015-05-27 15:42  techfox  阅读(495)  评论(0编辑  收藏  举报