Android記憶體最佳化的幾種代碼處理

來源:互聯網
上載者:User

Android記憶體最佳化的幾種代碼處理

以下為Androi記憶體最佳化的幾種代碼處理,範例程式碼,僅供參考:

?1. 產生Bitmap:

InputStream is =this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=newBitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; //width,hight設為原來的十分一
Bitmap btp =BitmapFactory.decodeStream(is,null,options);
2.回收Bitmap:

if(!bmp.isRecycle() ){
bmp.recycle() //回收圖片所佔的記憶體
system.gc() //提醒系統及時回收
}
?調用recycle(),會開啟一個線程去處理,具體什麼時候回收只有系統知道。(屬於建議 JVM 進行記憶體回收)
?這個就是為什麼我們有的地方調用了它,那個地方還是會報oom的原因。
?但是有總歸比沒有好,它可以有效減少oom的機率。
回收資源
(1)//用來存放圖片的緩衝
HashMapbitmapCache = new HashMap();
//如果沒有圖片,或者已經存在
if(bitmapCache.isEmpty() || !AppConst.bitmapCache.containsKey(position)){
bitmapCache.put(position,bm);
}
(2)定義FreeBitmap函數,在activity結束的時候,調用FreeBitmap函數, 回收map中的資源
private void FreeBitmap(HashMap cache){
if(cache.isEmpty()){
return;
}
for(Bitmap bitmap:cache.values()){
if(bitmap != null && !bitmap.isRecycled()){
bitmap.recycle();
}
}
cache.clear();
}

3.手動幹預堆記憶體:

(1)增強程式堆記憶體的處理效率:

開發一些大型遊戲或耗資源的應用時可考慮手動幹涉GC處理,如程式onCreate時調用VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);

(2)強行設定APP最小記憶體大小:

VMRuntime.getRuntime().setMinimumHeapSize(6* 1024* 1024); //設定最小heap記憶體為6MB大小

聯繫我們

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