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. //引用時    
  5. if(sr!=null){    
  6.     obj = sr.get();    
  7. }else{    
  8.     obj = new A();    
  9.     sr = new SoftReference(obj);    
  10. }    

    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.    
  3.     WeakReference wr = new WeakReference(obj);    
  4.    
  5.     obj = null;    
  6.    
  7.     //等待一段時間,obj對象就會被垃圾回收   
  8.   ...    
  9.    
  10.   if (wr.get()==null) {    
  11.   System.out.println("obj 已經被清除了 ");    
  12.   } else {    
  13.   System.out.println("obj 尚未被清除,其信息是 "+obj.toString());   
  14.   }   
  15.   ...   
  16. }   

 

    在此例中,透過 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.       
  6. public class Test {       
  7.     public static boolean isRun = true;       
  8.       
  9.     public static void main(String[] args) throws Exception {       
  10.         String abc = new String("abc");       
  11.         System.out.println(abc.getClass() + "@" + abc.hashCode());       
  12.         final ReferenceQueue referenceQueue = new ReferenceQueue<String>();       
  13.         new Thread() {       
  14.             public void run() {       
  15.                 while (isRun) {       
  16.                     Object o = referenceQueue.poll();       
  17.                     if (o != null) {       
  18.                         try {       
  19.                             Field rereferent = Reference.class      
  20.                                     .getDeclaredField("referent");       
  21.                             rereferent.setAccessible(true);       
  22.                             Object result = rereferent.get(o);       
  23.                             System.out.println("gc will collect:"      
  24.                                     + result.getClass() + "@"      
  25.                                     + result.hashCode());       
  26.                         } catch (Exception e) {       
  27.       
  28.                             e.printStackTrace();       
  29.                         }       
  30.                     }       
  31.                 }       
  32.             }       
  33.         }.start();       
  34.         PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc,       
  35.                 referenceQueue);       
  36.         abc = null;       
  37.         Thread.currentThread().sleep(3000);       
  38.         System.gc();       
  39.         Thread.currentThread().sleep(3000);       
  40.         isRun = false;       
  41.     }       
  42.       

 

 

結果爲

class java.lang.String@96354   

gc will collect:class java.lang.String@96354  好了,關於引用就講到這,下面看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.     }  
  26.     bitmapFactoryOptions.inJustDecodeBounds = false
  27.     bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), 
  28.             bitmapFactoryOptions); 
  29.     if(bmap != null){                
  30.         //ivwCouponImage.setImageBitmap(bmap); 
  31.         return bmap; 
  32.     } 
  33.     return null

     方式二代碼如下:

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

    上面兩種方式第一種直接使用邊界壓縮,第二種在使用邊界壓縮的情況下間接的使用了軟引用來避免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()  //提醒系統及時回收 

上面代碼與下面代碼大家可分開使用,也可有效緩解內存問題哦...吼吼...

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

   3:大家可以選擇在合適的地方使用以下代碼動態並自行顯式調用GC來回收內存:

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

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

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

  1. private final static 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);
發佈了22 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章