Android 記憶體問題的解決方案

來源:互聯網
上載者:User

標籤:

Android項目中由於載入的圖片比較多,所以經常報出記憶體溢出的錯誤,當項目中包含大量圖片,或者圖片過大,可能會oom,常用胡解決方案如下:

方法1 :  等比例縮小圖片  
                BitmapFactory.Options options = new BitmapFactory.Options();                options.inSampleSize = 4;


方法2 :  對圖片採用軟引用,及時地進行recyle()操作

              SoftReference<Bitmap> bitmap;              bitmap = new SoftReference<Bitmap>(pBitmap);         if(bitmap != null){              <span style="white-space:pre"></span>   if(bitmap.get() != null && !bitmap.get().isRecycled()){                   bitmap.get().recycle();                   bitmap = null;             }             }

方法3 :  對複雜的listview進行合理設計與編碼:

1.   注意重用Adapter裡面的 convertView  以及holder機制的運用 

public View getView(int position, View convertView, ViewGroup parent) {  if (convertView == null) {            v = mInflater.inflate(resource, parent, false);            final int[] to = mTo;            final int count = to.length;            final View[] holder = new View[count];            for (int i = 0; i < count; i++) {                holder[i] = v.findViewById(to[i]);            }    v.setTag(holder);        } else {        }    }


2.  上述方法嘗試還未成功,可用 lazy loading data 


方法4 : 單個頁面,橫豎屏切換N次後 OOM

1. 看看頁面配置當中有沒有大的圖片,比如背景圖之類的。去除xml中相關設定,改在程式中設定背景圖(放在onCreate()方法中):

<span style="white-space:pre"></span>Drawable bg = getResources().getDrawable(R.drawable.bg);        XXX.setBackgroundDrawable(rlAdDetailone_bg);
在Activity destory時注意,bg.setCallback(null); 防止Activity得不到及時的釋放 

2. 跟上面方法相似,直接把xml設定檔載入成view 再放到一個容器裡,然後直接調用 this.setContentView(View view);方法

         避免xml的重複載入


方法5 : 在頁面切換時儘可能少地重複使用一些代碼,比如:重複調用資料庫,反覆使用某些對象等等.....


方法6 :Android堆記憶體也可自己定義大小 和  最佳化Dalvik虛擬機器的堆記憶體配置

注意若使用這種方法:project build target 只能選擇 <= 2.2 版本,否則編譯將通不過。 所以不建議用這種方式 

     private final static int CWJ_HEAP_SIZE= 6*1024*1024; <span style="white-space:pre"></span>private final static float TARGET_HEAP_UTILIZATION = 0.75f;        VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);        VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);




  



Android 記憶體問題的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.