Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 教學:記憶體溢出(OOM)問題的解決方案總結

編輯:關於 Android 程式設計

本文總結了 Android 開發中記憶體溢出(OOM)的各種解決方案,分享給大家參考。

在近期開發的專案中發現,當載入的圖片太多或圖片過大時,經常出現 OOM 問題。網上資料提供了很多方法,但自己感覺有點雜亂,因此今天在三款不同型號的安卓手機上做了測試。由於既有效果也有結果,這裡做個詳細的總結,供大家共同交流學習,也供自己日後在解決 OOM 問題上有所提升。

一般遇到記憶體問題時,網上常見的做法大體有以下幾種:

一:在記憶體引用上做些處理,常用的有軟引用、虛引用、弱引用
二:在記憶體中載入圖片時直接做處理,如邊界壓縮
三:動態回收記憶體
四:優化 Dalvik 虛擬機的堆記憶體分配
五:自定義堆記憶體大小

可是真的有這麼簡單嗎?就用以上方式就能解決 OOM 了?其實不然,繼續來看。

下面照著上面的次序來整理幾種解決方式,數字序號與上面對應:

1:軟引用(SoftReference)、虛引用(PhantomReference)、弱引用(WeakReference)

這三個類別是對 heap 中 Java 物件的引用,透過它們可以與 GC 做簡單的交互,此外還有一個最常見的強引用。

1.1 強引用,例如下面程式碼:

 Object o=new Object(); Object o1=o; 

第一句是在 heap 堆中建立新的 Object 物件並透過 o 引用這個物件,第二句則透過 o 建立 o1 到 heap 堆中該物件的引用,這兩個引用都是強引用。只要存在對 heap 中物件的引用,GC 就不會收集該物件。若透過 o=null; o1=null,則可解除引用。

heap 中物件有強可及物件、軟可及物件、弱可及物件、虛可及物件與不可到達物件。引用的強弱順序是強、軟、弱、虛。對於一個物件屬於哪種可及物件,由它最強的引用決定:

 String abc=new String("abc"); //1 SoftReference<String> abcSoftRef=new SoftReference<String>(abc); //2 WeakReference<String> abcWeakRef = new WeakReference<String>(abc); //3 abc=null; //4 abcSoftRef.clear();//5 

第一行在 heap 堆中建立內容為「abc」的物件並建立 abc 到該物件的強引用,此時該物件是強可及的。第二、三行分別建立對 heap 中物件的軟引用與弱引用,此時 heap 中的物件仍是強可及的。第四行之後,heap 中物件不再是強可及,變成軟可及;同樣地,第五行執行之後變成弱可及。

1.2 軟引用:主要用於記憶體敏感的高速緩存。在 JVM 報告記憶體不足之前會清除所有的軟引用,這樣一來 GC 就有可能收集軟可及的物件,避免記憶體溢出。被 SoftReference 指到的物件,即使沒有任何 Direct Reference,也不會被清除,一直到 JVM 記憶體不足且沒有 Direct Reference 時才會清除。SoftReference 適合用來設計 object-cache。

 A obj = new A(); Refenrence sr = new SoftReference(obj); //引用時 if(sr!=null){ obj = sr.get(); }else{ obj = new A(); sr = new SoftReference(obj); } 

1.3 弱引用:當 GC 碰到弱可及物件並釋放 abcWeakRef 的引用時,便會收集該物件,但 GC 可能需要多次才能找到該弱可及物件。透過以下程式碼可以明顯看出它的作用:

 String abc=new String("abc"); WeakReference<String> abcWeakRef = new WeakReference<String>(abc); abc=null; System.out.println("before gc: "+abcWeakRef.get()); System.gc(); System.out.println("after gc: "+abcWeakRef.get()); 

運行結果:

before gc: abc
after gc: null

GC 收集弱可及物件的執行過程與軟可及一樣,只是 GC 不會根據記憶體情況來決定是否收集該物件。如果你希望能隨時取得某物件的信息,但又不想影響此物件的垃圾收集,那麼你應該用 WeakReference 來記住此物件,而不是用一般的 reference。

 A obj = new A(); WeakReference wr = new WeakReference(obj); obj = null; //等待一段時間,obj 物件就會被垃圾回收 ... if (wr.get()==null) { System.out.println("obj 已經被清除了"); } else { System.out.println("obj 尚未被清除,其信息是 "+obj.toString()); } ... } 

在此例中,透過 get() 可以取得此 Reference 所指到的物件,如果返回值為 null,代表此物件已經被清除。這類技巧在設計 Optimizer 或 Debugger 這類程式時常會用到,因為這類程式需要取得某物件的信息,但不可影響此物件的垃圾收集。

1.4 虛引用:顧名思義就是「沒有」的意思,建立虛引用之後透過 get 方法返回結果始終為 null。透過源碼你會發現,虛引用會把引用的物件寫進 referent,只是 get 方法返回結果為 null。它與 GC 交互的過程是:不把 referent 設置為 null,直接把 heap 中的物件設置為可結束的(finalizable),並先把 PhantomReference 物件添加到它的 ReferenceQueue 中,然後再釋放虛可及的物件。你會發現,在收集 heap 中的物件之前,你就可以做一些其他的事情。透過以下程式碼可以了解它的作用:

 import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.reflect.Field; public class Test { public static boolean isRun = true; public static void main(String[] args) throws Exception { String abc = new String("abc"); System.out.println(abc.getClass() + "@" + abc.hashCode()); final ReferenceQueue referenceQueue = new ReferenceQueue<String>(); new Thread() { public void run() { while (isRun) { Object o = referenceQueue.poll(); if (o != null) { try { Field rereferent = Reference.class .getDeclaredField("referent"); rereferent.setAccessible(true); Object result = rereferent.get(o); System.out.println("gc will collect:" + result.getClass() + "@" + result.hashCode()); } catch (Exception e) { e.printStackTrace(); } } } } }.start(); PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc, referenceQueue); abc = null; Thread.currentThread().sleep(3000); System.gc(); Thread.currentThread().sleep(3000); isRun = false; } } 

運行結果為:

class java.lang.String@96354
gc will collect:class java.lang.String@96354

2:在記憶體中壓縮

經過測試,對於少量不太大的圖片這種方式可行,但圖片太多又大時,可以先用個笨方式:先在記憶體中壓縮,再用軟引用避免 OOM。兩種方式程式碼如下,供大家參考:

方式一程式碼如下:

 @SuppressWarnings("unused") private Bitmap copressImage(String imgPath){ File picture = new File(imgPath); Options bitmapFactoryOptions = new BitmapFactory.Options(); //下面這個設置是將圖片邊界不可調節變為可調節 bitmapFactoryOptions.inJustDecodeBounds = true; bitmapFactoryOptions.inSampleSize = 2; int outWidth = bitmapFactoryOptions.outWidth; int outHeight = bitmapFactoryOptions.outHeight; bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); float imagew = 150; float imageh = 150; int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh); int xRatio = (int) Math .ceil(bitmapFactoryOptions.outWidth / imagew); if (yRatio > 1 || xRatio > 1) { if (yRatio > xRatio) { bitmapFactoryOptions.inSampleSize = yRatio; } else { bitmapFactoryOptions.inSampleSize = xRatio; } } bitmapFactoryOptions.inJustDecodeBounds = false; bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); if(bmap != null){ //ivwCouponImage.setImageBitmap(bmap); return bmap; } return null; } 

方式二程式碼如下:

 package com.lvguo.scanstreet.activity; import java.io.File; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import com.lvguo.scanstreet.R; import com.lvguo.scanstreet.data.ApplicationData; /** * @Title: PhotoScanActivity.java * @Description: 照片預覽控制類 * @author XiaoMa */ public class PhotoScanActivity extends Activity { private Gallery gallery ; private List<String> ImageList; private List<String> it ; private ImageAdapter adapter ; private String path ; private String shopType; private HashMap<String, SoftReference<Bitmap>> imageCache = null; private Bitmap bitmap = null; private SoftReference<Bitmap> srf = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.photoscan); Intent intent = this.getIntent(); if(intent != null){ if(intent.getBundleExtra("bundle") != null){ Bundle bundle = intent.getBundleExtra("bundle"); path = bundle.getString("path"); shopType = bundle.getString("shopType"); } } init(); } private void init(){ imageCache = new HashMap<String, SoftReference<Bitmap>>(); gallery = (Gallery)findViewById(R.id.gallery); ImageList = getSD(); if(ImageList.size() == 0){ Toast.makeText(getApplicationContext(), "無照片,請返回拍照後再使用預覽", Toast.LENGTH_SHORT).show(); return ; } adapter = new ImageAdapter(this, ImageList); gallery.setAdapter(adapter); gallery.setOnItemLongClickListener(longlistener); } /** * Gallery 長按事件操作實現 */ private OnItemLongClickListener longlistener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { //此處添加長按事件刪除照片實現 AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this); dialog.setIcon(R.drawable.warn); dialog.setTitle("刪除提示"); dialog.setMessage("你確定要刪除這張照片嗎?"); dialog.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File file = new File(it.get(position)); boolean isSuccess; if(file.exists()){ isSuccess = file.delete(); if(isSuccess){ ImageList.remove(position); adapter.notifyDataSetChanged(); //gallery.setAdapter(adapter); if(ImageList.size() == 0){ Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show(); } Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show(); } } } }); dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.create().show(); return false; } }; /** * 獲取 SD 卡上的所有圖片文件 * @return */ private List<String> getSD() { /* 設定目前所在路徑 */ File fileK ; it = new ArrayList<String>(); if("newadd".equals(shopType)){ //如果是從查看本人新增列表項或商戶列表項進來時 fileK = new File(ApplicationData.TEMP); }else{ //此時為純粹新增 fileK = new File(path); } File[] files = fileK.listFiles(); if(files != null && files.length>0){ for(File f : files ){ if(getImageFile(f.getName())){ it.add(f.getPath()); Options bitmapFactoryOptions = new BitmapFactory.Options(); //下面這個設置是將圖片邊界不可調節變為可調節 bitmapFactoryOptions.inJustDecodeBounds = true; bitmapFactoryOptions.inSampleSize = 5; int outWidth = bitmapFactoryOptions.outWidth; int outHeight = bitmapFactoryOptions.outHeight; float imagew = 150; float imageh = 150; int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh); int xRatio = (int) Math .ceil(bitmapFactoryOptions.outWidth / imagew); if (yRatio > 1 || xRatio > 1) { if (yRatio > xRatio) { bitmapFactoryOptions.inSampleSize = yRatio; } else { bitmapFactoryOptions.inSampleSize = xRatio; } } bitmapFactoryOptions.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(f.getPath(), bitmapFactoryOptions); //bitmap = BitmapFactory.decodeFile(f.getPath()); srf = new SoftReference<Bitmap>(bitmap); imageCache.put(f.getName(), srf); } } } return it; } /** * 獲取圖片文件方法的具體實現 * @param fName * @return */ private boolean getImageFile(String fName) { boolean re; /* 取得擴展名 */ String end = fName .substring(fName.lastIndexOf(".") + 1, fName.length()) .toLowerCase(); /* 按擴展名的類型決定 MimeType */ if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) { re = true; } else { re = false; } return re; } public class ImageAdapter extends BaseAdapter{ /* 聲明變量 */ int mGalleryItemBackground; private Context mContext; private List<String> lis; /* ImageAdapter 的構造符 */ public ImageAdapter(Context c, List<String> li) { mContext = c; lis = li; TypedArray a = obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } /* 幾定要重寫的方法 getCount,傳回圖片數目 */ public int getCount() { return lis.size(); } /* 一定要重寫的方法 getItem,傳回 position */ public Object getItem(int position) { return lis.get(position); } /* 一定要重寫的方法 getItemId,傳並 position */ public long getItemId(int position) { return position; } /* 幾定要重寫的方法 getView,傳並幾 View 對象 */ public View getView(int position, View convertView, ViewGroup parent) { System.out.println("lis:"+lis); File file = new File(it.get(position)); SoftReference<Bitmap> srf = imageCache.get(file.getName()); Bitmap bit = srf.get(); ImageView i = new ImageView(mContext); i.setImageBitmap(bit); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)); return i; } } } 

上面兩種方式中,第一種直接使用邊界壓縮,第二種則在使用邊界壓縮的情況下間接使用了軟引用來避免 OOM。但大家都知道,這些函數在完成 decode 後,最終都是透過 Java 層的 createBitmap 來完成的,需要消耗更多記憶體;若圖片多且大,這種方式還是會引起 OOM 異常。別著急,還有更多辦法:

1.

 InputStream is = this.getResources().openRawResource(R.drawable.pic1); BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 10; //width,hight 設為原來的十分一 Bitmap btp =BitmapFactory.decodeStream(is,null,options); 

2.

 if(!bmp.isRecycle() ){ bmp.recycle() //回收圖片所占的記憶體 system.gc() //提醒系統及時回收 } 

上面程式碼可與下面的程式碼分開使用,也能有效緩解記憶體問題:

 /** 以最省記憶體的方式讀取本地資源的圖片 */ public static Bitmap readBitMap(Context context, int resId){ BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //獲取資源圖片 InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is,null,opt); } 

3:動態並自行顯式呼叫 GC 來回收記憶體:

 if(bitmapObject.isRecycled()==false) //如果沒有回收 bitmapObject.recycle(); 

4:優化 Dalvik 虛擬機的堆記憶體分配。對於 Android 平台來說,其托管層使用的 Dalvik JavaVM 從目前表現來看還有很多可以優化的地方。比如在開發一些大型遊戲或耗資源的應用中,可能考慮手動干涉 GC 處理,使用 dalvik.system.VMRuntime 類別提供的 setTargetHeapUtilization 方法可以增強程式堆記憶體的處理效率。使用方法如下:

 private final static float TARGET_HEAP_UTILIZATION = 0.75f; //在程式 onCreate 時就可以調用 VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 

5:自定義應用需要多大的記憶體,強行設置最小記憶體大小:

 private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ; //設置最小 heap 記憶體為 6MB 大小 VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); 

好了,文章寫完了。因為涉及到的東西太多,所以篇幅有點長。這裡所講的東西還是會因為手機型號的不同而有所差異,大家得根據自己的需求選擇合適的方式來避免 OOM。大家加油,每天都有或多或少的收穫,這也算是進步!

希望本文所述能對大家的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved