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

android 常用解決內存溢出(OOM)的方法

編輯:關於 Android 程式設計

已經遇到過很多次內存溢出了,必須好好總結吸取教訓!下面整理一些行之有效的 OOM 應對手段。

一、首要目標:Bitmap

Bitmap 常常是造成 OOM 的罪魁禍首,必須優先處理。原則是:作用域能小就小,用完就趕緊 recycle 掉。我一般會在 onDestroy 裡統一回收:

//回收圖片資源

if(bitmaps != null && bitmaps.length > 0){

int length = bitmaps.length;

for(int i=0; i<length; i++){

if(bitmaps[i] != null && !bitmaps[i].isRecycled()){

bitmaps[i].recycle();

}

}

}

二、清理 ViewGroup 的子 View

如果用到 ListView、GridView 等 ViewGroup 子類,記得移除它的 ChildView,並把相關集合置空,因為這些也很佔內存:

int listViewCount = dataList.size();

if(listView != null && (dataList != null && listViewCount>0)){

for(int i=0; i<listViewCount; i++){

dataList.removeAll(dataList);

adapter.notifyDataSetChanged();

}

}

listView = null;

dataList = null;

這兩段代碼我都直接放在 onDestroy 裡執行,效果還不錯,至少不容易崩。

三、其他常見手段

解決 OOM 的方法還有很多,下面再補充兩種。

WeakReference(弱引用):把可能被回收的對象用弱引用包裹,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());

壓縮 Bitmap:通過 inSampleSize 對圖片進行抽樣縮放,能顯著降低加載大圖時的內存佔用:

BitmapFactory.Options opts = new BitmapFactory.Options();

opts.inSampleSize = 4;

opts.inJustDecodeBounds = false;

Bitmap bitmap = BitmapFactory.decodeFile(filepath, opts);

把這些方法結合使用,就能在很大程度上避免 OOM。Good Luck!

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