1. 程式人生 > >Android之解決太大太多圖片造成的oom

Android之解決太大太多圖片造成的oom

在最近做的工程中發現載入的圖片太多或圖片過大時經常出現OOM問題,找網上資料也提供了很多方法,但自己感覺有點亂,特此,今天在不同型號的三款安卓手機上做了測試,因為有效果也有結果,今天小馬就做個詳細的總結,以供朋友們共同交流學習,也供自己以後在解決OOM問題上有所提高,提前講下,片幅有點長,涉及的東西太多,大家耐心看,肯定有收穫的,裡面的很多東西小馬也是學習參考網路資料使用的,先來簡單講下下:

   一般我們大家在遇到記憶體問題的時候常用的方式網上也有相關資料,大體如下幾種:

   一:在記憶體引用上做些處理,常用的有軟引用、強化引用、弱引用

   二:在記憶體中載入圖片時直接在記憶體中做處理,如:邊界壓縮

   三:動態回收記憶體

   四:優化Dalvik虛擬機器的堆記憶體分配

   五:自定義堆記憶體大小

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

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

   1:軟引用(SoftReference)、虛引用(PhantomRefrence)、弱引用(WeakReference),這三個類是對heap中java物件的應用,通過這個三個類可以和gc做簡單的互動,除了這三個以外還有一個是最常用的強引用

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

  1. Object o=new Object();      
  2. Object o1=o;  

     上面程式碼中第一句是在heap堆中建立新的Object物件通過o引用這個物件,第二句是通過o建立o1到new Object()這個heap堆中的物件的引用,這兩個引用都是強引用.只要存在對heap中物件的引用,gc就不會收集該物件.如果通過如下程式碼:

  1. o=null;      
  2. o1=null

      heap中物件有強可及物件、軟可及物件、弱可及物件、虛可及物件和不可到達物件。應用的強弱順序是強、軟、弱、和虛。對於物件是屬於哪種可及的物件,由他的最強的引用決定。如下:

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

上面的程式碼中:

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

        1.2:軟引用

               軟引用是主要用於記憶體敏感的快取記憶體。在jvm報告記憶體不足之前會清除所有的軟引用,這樣以來gc就有可能收集軟可及的物件,可能解決記憶體吃緊問題,避免記憶體溢位。什麼時候會被收集取決於gc的演算法和gc執行時可用記憶體的大小。當gc決定要收集軟引用是執行以下過程,以上面的abcSoftRef為例:

    1 首先將abcSoftRef的referent設定為null,不再引用heap中的new String("abc")物件。

    2 將heap中的new String("abc")物件設定為可結束的(finalizable)。

    3 當heap中的new String("abc")物件的finalize()方法被執行而且該物件佔用的記憶體被釋放, abcSoftRef被新增到它的ReferenceQueue中。

   注:對ReferenceQueue軟引用和弱引用可以有可無,但是虛引用必須有,參見:

  1. Reference(T paramT, ReferenceQueue<? super T>paramReferenceQueue) 

被 Soft Reference 指到的物件,即使沒有任何 Direct Reference,也不會被清除。一直要到 JVM 記憶體不足且 沒有 Direct Reference 時才會清除,SoftReference 是用來設計 object-cache 之用的。如此一來 SoftReference 不但可以把物件 cache 起來,也不會造成記憶體不足的錯誤 (OutOfMemoryError)。我覺得 Soft Reference 也適合拿來實作 pooling 的技巧。

  1. A obj = new A();   
  2. Refenrence sr = new SoftReference(obj);   
  3. //引用時  
  4. if(sr!=null){   
  5.     obj = sr.get();   
  6. }else{   
  7.     obj = new A();   
  8.     sr = new SoftReference(obj);   
  9. }   

    1.3:弱引用

當gc碰到弱可及物件,並釋放abcWeakRef的引用,收集該物件。但是gc可能需要對此運用才能找到該弱可及物件。通過如下程式碼可以了明瞭的看出它的作用:

  1. String abc=new String("abc");      
  2. WeakReference<String> abcWeakRef = new WeakReference<String>(abc);      
  3. abc=null;      
  4. System.out.println("before gc: "+abcWeakRef.get());      
  5. System.gc();      
  6. System.out.println("after gc: "+abcWeakRef.get());   

執行結果:   

before gc: abc   

after gc: null  

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

  1. A obj = new A();   
  2.     WeakReference wr = new WeakReference(obj);   
  3.     obj = null;   
  4.     //等待一段時間,obj物件就會被垃圾回收 
  5.   ...   
  6.   if (wr.get()==null) {   
  7.   System.out.println("obj 已經被清除了 ");   
  8.   } else {   
  9.   System.out.println("obj 尚未被清除,其資訊是 "+obj.toString());  
  10.   }  
  11.   ...  
  12. }  

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

     1.4:虛引用

     就是沒有的意思,建立虛引用之後通過get方法返回結果始終為null,通過原始碼你會發現,虛引用通向會把引用的物件寫進referent,只是get方法返回結果為null.先看一下和gc互動的過程在說一下他的作用.

      1.4.1 不把referent設定為null, 直接把heap中的new String("abc")物件設定為可結束的(finalizable).

      1.4.2 與軟引用和弱引用不同, 先把PhantomRefrence物件新增到它的ReferenceQueue中.然後在釋放虛可及的物件.

   你會發現在收集heap中的new String("abc")物件之前,你就可以做一些其他的事情.通過以下程式碼可以瞭解他的作用.

  1. import java.lang.ref.PhantomReference;      
  2. import java.lang.ref.Reference;      
  3. import java.lang.ref.ReferenceQueue;      
  4. import java.lang.reflect.Field;      
  5. publicclass Test {      
  6.     publicstaticboolean isRun = true;      
  7.     publicstaticvoid main(String[] args) throws Exception {      
  8.         String abc = new String("abc");      
  9.         System.out.println(abc.getClass() + "@" + abc.hashCode());      
  10.         final ReferenceQueue referenceQueue =new ReferenceQueue<String>();      
  11.         new Thread() {      
  12.             publicvoid run() {      
  13.                 while (isRun) {      
  14.                     Object o = referenceQueue.poll();      
  15.                     if (o !=null) {      
  16.                         try {      
  17.                             Field rereferent = Reference.class
  18.                                     .getDeclaredField("referent");      
  19.                             rereferent.setAccessible(true);      
  20.                             Object result = rereferent.get(o);      
  21.                             System.out.println("gc will collect:"
  22.                                     + result.getClass() + "@"
  23.                                     + result.hashCode());      
  24.                         } catch (Exception e) {      
  25.                             e.printStackTrace();      
  26.                         }      
  27.                     }      
  28.                 }      
  29.             }      
  30.         }.start();      
  31.         PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc,      
  32.                 referenceQueue);      
  33.         abc = null;      
  34.         Thread.currentThread().sleep(3000);      
  35.         System.gc();      
  36.         Thread.currentThread().sleep(3000);      
  37.         isRun = false;      
  38.     }      
  39. }

結果為

class [email protected]  

gc will collect:class [email protected]  好了,關於引用就講到這,下面看2

   2:在記憶體中壓縮小馬做了下測試,對於少量不太大的圖片這種方式可行,但太多而又大的圖片小馬用個笨的方式就是,先在記憶體中壓縮,再用軟引用避免OOM,兩種方式程式碼如下,大家可參考下:

     方式一程式碼如下:

  1. @SuppressWarnings("unused")
  2. private Bitmap copressImage(String imgPath){
  3.     File picture = new File(imgPath);
  4.     Options bitmapFactoryOptions = new BitmapFactory.Options();
  5.     //下面這個設定是將圖片邊界不可調節變為可調節
  6.     bitmapFactoryOptions.inJustDecodeBounds = true;
  7.     bitmapFactoryOptions.inSampleSize = 2;
  8.     int outWidth  = bitmapFactoryOptions.outWidth;
  9.     int outHeight = bitmapFactoryOptions.outHeight;
  10.     bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
  11.          bitmapFactoryOptions);
  12.     float imagew = 150;
  13.     float imageh = 150;
  14.     int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
  15.             / imageh);
  16.     int xRatio = (int) Math
  17.             .ceil(bitmapFactoryOptions.outWidth / imagew);
  18.     if (yRatio > 1 || xRatio >1) {
  19.         if (yRatio > xRatio) {
  20.             bitmapFactoryOptions.inSampleSize = yRatio;
  21.         } else {
  22.             bitmapFactoryOptions.inSampleSize = xRatio;
  23.         }
  24.     } 
  25.     bitmapFactoryOptions.inJustDecodeBounds = false;
  26.     bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
  27.             bitmapFactoryOptions);
  28.     if(bmap != null){               
  29.         //ivwCouponImage.setImageBitmap(bmap);
  30.         return bmap;
  31.     }
  32.     returnnull;
  33. }

     方式二程式碼如下:

  1. package com.lvguo.scanstreet.activity;
  2. import java.io.File;
  3. import java.lang.ref.SoftReference;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import android.app.Activity;
  8. import android.app.AlertDialog;
  9. import android.content.Context;
  10. import android.content.DialogInterface;
  11. import android.content.Intent;
  12. import android.content.res.TypedArray;
  13. import android.graphics.Bitmap;
  14. import android.graphics.BitmapFactory;
  15. import android.graphics.BitmapFactory.Options;
  16. import android.os.Bundle;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.view.WindowManager;
  20. import android.widget.AdapterView;
  21. import android.widget.AdapterView.OnItemLongClickListener;
  22. import android.widget.BaseAdapter;
  23. import android.widget.Gallery;
  24. import android.widget.ImageView;
  25. import android.widget.Toast;
  26. import com.lvguo.scanstreet.R;
  27. import com.lvguo.scanstreet.data.ApplicationData;
  28. /** 
  29. * @Title: PhotoScanActivity.java
  30. * @Description: 照片預覽控制類
  31. * @author XiaoMa 
  32. */
  33. publicclass PhotoScanActivityextends Activity {
  34.     private Gallery gallery ;
  35.     private List<String> ImageList;
  36.     private List<String> it ;
  37.     private ImageAdapter adapter ; 
  38.     private String path ;
  39.     private String shopType;
  40.     private HashMap<String, SoftReference<Bitmap>> imageCache =null;
  41.     private Bitmap bitmap = null;
  42.     private SoftReference<Bitmap> srf =null;
  43.     @Override
  44.     publicvoid onCreate(Bundle savedInstanceState) {
  45.         super.onCreate(savedInstanceState);
  46.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
  47.         WindowManager.LayoutParams.FLAG_FULLSCREEN); 
  48.         setContentView(R.layout.photoscan);
  49.         Intent intent = this.getIntent();
  50.         if(intent != null){
  51.             if(intent.getBundleExtra("bundle") !=null){
  52.                 Bundle bundle = intent.getBundleExtra("bundle");
  53.                 path = bundle.getString("path");
  54.                 shopType = bundle.getString("shopType");
  55.             }
  56.         }
  57.         init();
  58.     }
  59.     privatevoid init(){
  60.         imageCache = new HashMap<String, SoftReference<Bitmap>>();
  61.          gallery = (Gallery)findViewById(R.id.gallery);
  62.          ImageList = getSD();
  63.          if(ImageList.size() == 0){
  64.             Toast.makeText(getApplicationContext(), "無照片,請返回拍照後再使用預覽", Toast.LENGTH_SHORT).show();
  65.             return ;
  66.          }
  67.          adapter = new ImageAdapter(this, ImageList);
  68.          gallery.setAdapter(adapter);
  69.          gallery.setOnItemLongClickListener(longlistener);
  70.     }
  71.     /**
  72.      * Gallery長按事件操作實現
  73.      */
  74.     private OnItemLongClickListener longlistener =new OnItemLongClickListener() {
  75.         @Override
  76.         publicboolean onItemLongClick(AdapterView<?> parent, View view,
  77.                 final int position, long id) {
  78.             //此處新增長按事件刪除照片實現
  79.             AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this);
  80.             dialog.setIcon(R.drawable.warn);
  81.             dialog.setTitle("刪除提示");
  82.             dialog.setMessage("你確定要刪除這張照片嗎?");
  83.             dialog.setPositiveButton("確定",new DialogInterface.OnClickListener() {
  84.                 @Override
  85.                 public void onClick(DialogInterface dialog, int which) {
  86.                     File file = new File(it.get(position));
  87.                     boolean isSuccess;
  88.                     if(file.exists()){
  89.                         isSuccess = file.delete();
  90.                         if(isSuccess){
  91.                             ImageList.remove(position);
  92.                             adapter.notifyDataSetChanged();
  93.                             //gallery.setAdapter(adapter);
  94.                             if(ImageList.size() ==0){
  95.                                 Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show();
  96.                             }
  97.                             Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show();
  98.                         }
  99.                     }
  100.                 }
  101.             });
  102.             dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
  103.                 @Override
  104.                 publicvoid onClick(DialogInterface dialog,int which) {
  105.                     dialog.dismiss();
  106.                 }
  107.             });
  108.             dialog.create().show();
  109.             return false;
  110.         }
  111.     };
  112.     /**
  113.      * 獲取SD卡上的所有圖片檔案
  114.      * @return
  115.      */
  116.     private List<String> getSD() {
  117.         /* 設定目前所在路徑 */
  118.         File fileK ;
  119.         it = new ArrayList<String>();
  120.         if("newadd".equals(shopType)){ 
  121.              //如果是從檢視本人新增列表項或商戶列表項進來時
  122.             fileK = new File(ApplicationData.TEMP);
  123.         }else{
  124.             //此時為純粹新增
  125.             fileK = new File(path);
  126.         }
  127.         File[] files = fileK.listFiles();
  128.         if(files != null && files.length>0){
  129.             for(File f : files ){
  130.                 if(getImageFile(f.getName())){
  131.                     it.add(f.getPath());
  132.                     Options bitmapFactoryOptions = new BitmapFactory.Options();
  133.                     //下面這個設定是將圖片邊界不可調節變為可調節
  134.                     bitmapFactoryOptions.inJustDecodeBounds = true;
  135.                     bitmapFactoryOptions.inSampleSize = 5;
  136.                     int outWidth  = bitmapFactoryOptions.outWidth;
  137.                     int outHeight = bitmapFactoryOptions.outHeight;
  138.                     float imagew = 150;
  139.                     float imageh =150;
  140.                     int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
  141.                             / imageh);
  142.                     int xRatio = (int) Math
  143.                             .ceil(bitmapFactoryOptions.outWidth / imagew);
  144.                     if (yRatio > 1 || xRatio > 1) {
  145.                         if (yRatio > xRatio) {
  146.                             bitmapFactoryOptions.inSampleSize = yRatio;
  147.                         } else {
  148.                             bitmapFactoryOptions.inSampleSize = xRatio;
  149.                         }
  150.                     } 
  151.                     bitmapFactoryOptions.inJustDecodeBounds = false;
  152.                     bitmap = BitmapFactory.decodeFile(f.getPath(),
  153.                             bitmapFactoryOptions);
  154.                     //bitmap = BitmapFactory.decodeFile(f.getPath());
  155.                     srf = new SoftReference<Bitmap>(bitmap);
  156.                     imageCache.put(f.getName(), srf);
  157.                 }
  158.             }
  159.         }
  160.         return it;
  161.     }
  162.     /**
  163.      * 獲取圖片檔案方法的具體實現
  164.      * @param fName
  165.      * @return
  166.      */
  167.     privateboolean getImageFile(String fName) {
  168.         boolean re;
  169.         /* 取得副檔名 */
  170.         String end = fName
  171.                 .substring(fName.lastIndexOf(".") +1, fName.length())
  172.                 .toLowerCase();
  173.         /* 按副檔名的型別決定MimeType */
  174.         if (end.equals("jpg") || end.equals("gif") || end.equals("png")
  175.                 || end.equals("jpeg") || end.equals("bmp")) {
  176.             re = true;
  177.         } else {
  178.             re = false;
  179.         }
  180.         return re;
  181.     }
  182.     publicclass ImageAdapterextends BaseAdapter{
  183.         /* 宣告變數 */
  184.         int mGalleryItemBackground;
  185.         private Context mContext;
  186.         private List<String> lis;
  187.         /* ImageAdapter的構造符 */
  188.         public ImageAdapter(Context c, List<String> li) {
  189.             mContext = c;
  190.             lis = li;
  191.             TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
  192.             mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground,0);
  193.             a.recycle();
  194.         }
  195.         /* 幾定要重寫的方法getCount,傳回圖片數目 */
  196.         publicint getCount() {
  197.             return lis.size();
  198.         }
  199.         /* 一定要重寫的方法getItem,傳回position */
  200.         public Object getItem(int position) {
  201.             return lis.get(position);
  202.         }
  203.         /* 一定要重寫的方法getItemId,傳並position */
  204.         publiclong getItemId(int position) {
  205.             return position;
  206.         }
  207.         /* 幾定要重寫的方法getView,傳並幾View物件 */
  208.         public View getView(int position, View convertView, ViewGroup parent) {
  209.             System.out.println("lis:"+lis);
  210.             File file = new File(it.get(position));
  211.             SoftReference<Bitmap> srf = imageCache.get(file.getName());
  212.             Bitmap bit = srf.get();
  213.             ImageView i = new ImageView(mContext);
  214.             i.setImageBitmap(bit);
  215.             i.setScaleType(ImageView.ScaleType.FIT_XY);
  216.             i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
  217.                     WindowManager.LayoutParams.WRAP_CONTENT));
  218.             return i;
  219.         }
  220.     }
  221. }

    上面兩種方式第一種直接使用邊界壓縮,第二種在使用邊界壓縮的情況下間接的使用了軟引用來避免OOM,但大家都知道,這些函式在完成decode後,最終都是通過java層的createBitmap來完成的,需要消耗更多記憶體,如果圖片多且大,這種方式還是會引用OOM異常的,不著急,有的是辦法解決,繼續看,以下方式也大有妙用的:

  1. 1. InputStream is =this.getResources().openRawResource(R.drawable.pic1);
  2.      BitmapFactory.Options options=new BitmapFactory.Options();
  3.      options.inJustDecodeBounds =false;
  4.      options.inSampleSize = 10;   //width,hight設為原來的十分一
  5.      Bitmap btp =BitmapFactory.decodeStream(is,null,options);
  6. 2. if(!bmp.isRecycle() ){
  7.          bmp.recycle()   //回收圖片所佔的記憶體
  8.          system.gc()  //提醒系統及時回收
  9. }

上面程式碼與下面程式碼大家可分開使用,也可有效緩解記憶體問題哦...吼吼...

  1.     /** 這個地方大家別搞混了,為了方便小馬把兩個貼一起了,使用的時候記得分開使用
  2.      * 以最省記憶體的方式讀取本地資源的圖片
  3.      */  
  4.     public static Bitmap readBitMap(Context context, int resId){  
  5.         BitmapFactory.Options opt =new BitmapFactory.Options();  
  6.         opt.inPreferredConfig = Bitmap.Config.RGB_565;   
  7.        opt.inPurgeable =true;  
  8.        opt.inInputShareable = true;  
  9.           //獲取資源圖片  
  10.        InputStream is = context.getResources().openRawResource(resId);  
  11.            return BitmapFactory.decodeStream(is,null,opt);  
  12.    }

   3:大家可以選擇在合適的地方使用以下程式碼動態並自行顯式呼叫GC來回收記憶體:

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

   4:這個就好玩了,優化Dalvik虛擬機器的堆記憶體分配,聽著很強大,來看下具體是怎麼一回事

     對於Android平臺來說,其託管層使用的Dalvik JavaVM從目前的表現來看還有很多地方可以優化處理,比如我們在開發一些大型遊戲或耗資源的應用中可能考慮手動干涉GC處理,使用 dalvik.system.VMRuntime類提供的setTargetHeapUtilization方法可以增強程式堆記憶體的處理效率。當然具體原理我們可以參考開源工程,這裡我們僅說下使用方法:程式碼如下:

  1. privatefinalstatic floatTARGET_HEAP_UTILIZATION = 0.75f; 
  2. 在程式onCreate時就可以呼叫
  3. VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
  4. 即可

   5:自定義我們的應用需要多大的記憶體,這個好暴力哇,強行設定最小記憶體大小,程式碼如下:

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