android記憶體溢出的解決方案

來源:互聯網
上載者:User

1. 當項目中包含大量圖片,或者圖片過大

方法1:等比例縮小圖片

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4

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

SoftReference<Bitmap> bitmap;
bitmap = new SoftReference<Bitmap>(pBitmap);
if(bitmap != null){
if(bitmap.get() != null && !bitmap.get().isRecycled()){
bitmap.get().recycle();
bitmap = null;
}
}


方法3 : 對複雜的listview進行合理設計與編碼(個人感覺這個靠譜點)1. 注意重用Adapter裡面的convertView,以及holder機制的運用
上述方法嘗試還未成功,可用 lazy loading data

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 {
}
}



方法4 : 單個頁面,橫豎屏切換N次後 OOM
1. 看看頁面配置當中有沒有大的圖片,比如背景圖之類的。去除xml中相關設定,改在程式中設定背景圖(放在onCreate()方法中):

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虛擬機器的記憶體


private final static int CWJ_HEAP_SIZE= 6*1024*1024;

private final static float TARGET_HEAP_UTILIZATION = 0.75f;
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.