一、原因
1察纯、內(nèi)存泄漏導(dǎo)致
頻繁的內(nèi)存泄漏將會(huì)引發(fā)內(nèi)存溢出帕棉;
2、占用內(nèi)存較多的對(duì)象
保存了多個(gè)耗用內(nèi)存較多的對(duì)象(如Bitmap)饼记;
加載超大的圖片香伴;
二、解決方案
1具则、內(nèi)存泄漏導(dǎo)致的OOM瞒窒,可參考Android常見(jiàn)問(wèn)題之內(nèi)存泄漏
2、加載超大圖片造成的OOM解決方案:
1)等比例縮小圖片
使用setImageBitmap或setImageResource或BitmapFactory.decodeResource設(shè)置大圖時(shí)乡洼,這些函數(shù)在完成decode后崇裁,最終都是通過(guò)java層的createBitmap來(lái)完成的,需要消耗更多內(nèi)存束昵。
public static Bitmap scaleImage(Bitmap bitmap, int newWidth, int newHeight) {
if (bitmap == null) {
return null;
}
float scaleWidth = (float) newWidth / bitmap.getWidth();
float scaleHeight = (float) newHeight / bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
2)對(duì)圖片采用軟引用拔稳,及時(shí)地進(jìn)行recycle()操作
雖然系統(tǒng)能夠確認(rèn)Bitmap分配的內(nèi)存最終會(huì)被銷毀,但是由于它占用的內(nèi)存過(guò)多锹雏,所以很可能會(huì)超過(guò)java堆的限制巴比。因此,在用完Bitmap時(shí)要及時(shí)的recycle掉。recycle并不能確定立即就會(huì)將Bitmap釋放掉轻绞,但是會(huì)給虛擬機(jī)一個(gè)暗示:“該圖片可以釋放了”采记。
SoftReference<Bitmap> bitmap;
bitmap = new SoftReference<>(pBitmap);
if(bitmap != null){
if(bitmap.get() != null && !bitmap.get().isRecycled()){
bitmap.get().recycle();
bitmap = null;
}
}
3)避免XML的重復(fù)加載
因?yàn)閱蝹€(gè)頁(yè)面橫豎屏切換多次后,會(huì)出現(xiàn)OOM的情況政勃。
所以當(dāng)頁(yè)面布局中存在較大的圖片時(shí)唧龄,應(yīng)該去除xml中相關(guān)設(shè)置,改在程序中設(shè)置背景圖奸远;
ImageView imageView= (ImageView) findViewById(R.id.image_test);
imageView.setBackground(getDrawable(R.mipmap.ic_launcher));
或者直接把xml配置文件加載成view 再放到一個(gè)容器里既棺,然后直接調(diào)用 this.setContentView(View view)