Android Bitmap OutOfMemory 解决的方法
????? 在Android應(yīng)用里,最耗費(fèi)內(nèi)存的就是圖片資源。并且在Android系統(tǒng)中。讀取位圖Bitmap時(shí),分給虛擬機(jī)中的圖片的堆棧大小僅僅有8M。假設(shè)超出了。就會(huì)出現(xiàn)OutOfMemory異常
E/AndroidRuntime(? 697): java.lang.OutOfMemoryError
E/AndroidRuntime(? 697): ?? ?at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
E/AndroidRuntime(? 697): ?? ?at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:500)
E/AndroidRuntime(? 697): ?? ?at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:353)
E/AndroidRuntime(? 697): ?? ?at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:376)
E/AndroidRuntime(? 697): ?? ?at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:406)
E/AndroidRuntime(? 697): ?? ?at com.example.imagetoshow2.ImageAdapter.createReflectedImages(ImageAdapter.java:66)
E/AndroidRuntime(? 697): ?? ?at com.example.imagetoshow2.ImageAdapter.getView(ImageAdapter.java:54)
E/AndroidRuntime(? 697): ?? ?at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
解決的方法:
1.及時(shí)回收內(nèi)存
if(bitmap != null && !bitmap.isRecycled()){ // 回收而且置為nullbitmap.recycle(); bitmap = null; } System.gc();在適當(dāng)?shù)牡胤绞褂蒙鲜龃a,將臨時(shí)不需使用的的回收掉。當(dāng)然system.gc不應(yīng)該頻繁調(diào)用,否則會(huì)使系統(tǒng)效率減少。2.使用BitmapFactory.Options對(duì)圖片進(jìn)行壓縮
BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = n; bitmap = BitmapFactory.decodeStream(fis, null, opts);
使用inSampleSize設(shè)置放縮比例,默認(rèn)值為0,設(shè)置一個(gè)大于0的數(shù)便可對(duì)圖片進(jìn)行壓縮。
BitmapFactory.Options opts = new BitmapFactory.Options();// 設(shè)置inJustDecodeBounds為trueopts.inJustDecodeBounds = true;// 使用decodeFile方法得到圖片的寬和高BitmapFactory.decodeFile(path, opts);
使inJustDecodeBounds為true后,再使用decodeFile()等方法,并不會(huì)真正的分配空間,即解碼出來(lái)的Bitmap為null。僅僅會(huì)計(jì)算出options.outWidth和options.outHeight值。在下次使用BitmapFactory的decodeFile()等方法實(shí)例化Bitmap對(duì)象前。將opts.inJustDecodeBound設(shè)置回false就能夠得到圖片了。
3.代碼優(yōu)化
為了避免應(yīng)用在分配Bitmap內(nèi)存的時(shí)候出現(xiàn)OutOfMemory異常停止執(zhí)行。通常。在實(shí)例化Bitmap的代碼中,對(duì)OutOfMemory異常進(jìn)行捕獲
<span style="font-size:18px;"> <span style="font-size:18px;">Bitmap bitmap = null; try {// 實(shí)例化Bitmapbitmap = BitmapFactory.decodeFile(path); } catch (OutOfMemoryError e) {// }</span></span>然后在Catch部分做一些內(nèi)存回收操作。或者是使用緩存圖片等...總是良好的編程風(fēng)格和優(yōu)質(zhì)的代碼結(jié)構(gòu)是程序猿的無(wú)上追求....
轉(zhuǎn)載于:https://www.cnblogs.com/mengfanrong/p/5055139.html
總結(jié)
以上是生活随笔為你收集整理的Android Bitmap OutOfMemory 解决的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。