Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 內存溢出(OOM)問題解決方案大全

編輯:Android 開發實例

本文為大家總結了 Android 開發中內存溢出(OOM)的常見解決方案,希望對正在被 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 中對象還存在強引用,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 建立強引用,此時對象是強可及的;第二、三行分別建立了軟引用和弱引用,但對象仍是強可及的;執行第四行之後,對象不再強可及,變為軟可及;第五行執行後則變為弱可及。

1.2 軟引用

軟引用主要用於內存敏感的高速緩存。在 JVM 報告內存不足之前,它會清除所有軟引用,讓 GC 有機會回收軟可及對象,從而緩解內存吃緊、避免溢出。具體何時被回收,取決於 GC 算法與運行時可用內存的大小。以 abcSoftRef 為例,GC 決定回收時會:

1. 先把 abcSoftRef 的 referent 設為 null,不再引用 heap 中的對象;
2. 將該對象設為可結束的(finalizable);
3. 當 finalize() 執行完畢、內存被釋放後,abcSoftRef 會被加入它的 ReferenceQueue。

補充:ReferenceQueue 對軟引用和弱引用可有可無,但虛引用必須具備。被 SoftReference 指向的對象,即使沒有任何直接引用,也不會立刻被清除,而是要等到 JVM 內存不足且無直接引用時才回收,因此它非常適合實現 object-cache 或 pooling。

 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 碰到弱可及對象時,會直接釋放引用並回收該對象(可能需要多次 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 回收弱可及對象的過程與軟可及一致,只是它不會根據內存情況來決定是否回收。如果你希望能隨時取得某對象的信息,但又不想影響它被回收,就應該用 WeakReference 來記錄它,而不是普通引用。

 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() 可以取得該引用指向的對象,若返回 null 就代表對象已被清除。這類技巧常用於設計 Optimizer、Debugger 等程序,因為它們既要取得對象信息,又不能干擾對象的垃圾回收。

1.4 虛引用

虛引用顧名思義就是「沒有」的意思,建立虛引用後,get() 方法始終返回 null。它與 GC 的交互過程是:先把 heap 中的對象設為可結束的,再將 PhantomReference 對象加入 ReferenceQueue,最後才釋放虛可及對象。也就是說,在對象真正被回收之前,你就能做一些收尾工作。示例如下:

 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){ 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; 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); } 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(); 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; } }; 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); srf = new SoftReference<Bitmap>(bitmap); imageCache.put(f.getName(), srf); } } } return it; } private boolean getImageFile(String fName) { boolean re; String end = fName .substring(fName.lastIndexOf(".") + 1, fName.length()) .toLowerCase(); 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; 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(); } public int getCount() { return lis.size(); } public Object getItem(int position) { return lis.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { 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。別急,還有更多辦法。

下面的代碼可以分開使用,也能有效緩解內存壓力:

 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); 
 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