安卓開發中應注意內存的釋放,一旦加載圖片或其他占用太多內存,此時就會發生OOM錯誤,即內存泄露。
在開發中,尤其應注意圖片資源的釋放。 1。背景圖片和ImageView釋放------尤其注意圖片資源 如: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/main_background"
android:id="@+id/mian_bg"
android:scaleType="fitXY"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:layout_gravity="center"
android:src="@drawable/img_main_roll0"
android:id="@+id/main_cion"
android:layout_width="180dp"
android:layout_height="180dp"/>
</<LinearLayout>
先獲取圖片控件:
public ImageView p_w_picpathView;
public LinearLayout linearLayout;
p_w_picpathView=(ImageView)findViewById(R.id.main_cion);
linearLayout=(LinearLayout)findViewById(R.id.mian_bg);
應在次Activity銷毀時釋放
protected void onDestroy() {
super.onDestroy();
p_w_picpathView.setImageBitmap(null);//釋放
linearLayout.setBackground(null);
System.gc();//通知進行回收
}
使用Bitmap記得不用時調用回收
bitmap.recycle();
總結:
無論你是在xml中布局使用了:
android:background ,
還是在java代碼中調用了:
setBackground( background );-------API16+
setBackgroundDrawable( background)--------API16-
setBackgroundResource( resid)
的方式去設置了背景圖片.
使用的時候,請調用一下對應的方法:
setBackgroundResource和 android:background → setBackgroundResource(0);
setBackgroundDrawable( background) → setBackgroundDrawable (null)
setBackground ( background ) → setBackground ( null )
然后再onDestory中調用System.gc();
復制代碼 2.確定不用的List,數組等參數 釋放:Obj=null即可,list先clear(),在令其等于null;如內存緊張,可及時調用Syetem.gc()通知進行回收 |