最近在幫一個朋友寫一個android 軟件,頻繁的用ImageView 更換圖片。
結果常常出現OOM
後來修改把ImageView加載圖片自己來管理,問題解決了,不敢獨享,拿出來與各位同學分享
private void showImage(int index) {
int resid = R.drawable.circle_01;
switch (index) {
case 1:
resid = R.drawable.circle_01;
break;
case 2:
resid = R.drawable.circle_02;
break;
case 3:
resid = R.drawable.circle_03;
break;
case 4:
resid = R.drawable.circle_04;
break;
case 5:
resid = R.drawable.circle_05;
break;
case 6:
resid = R.drawable.circle_06;
break;
case 7:
resid = R.drawable.circle_07;
break;
case 8:
resid = R.drawable.circle_08;
break;
case 9:
resid = R.drawable.circle_09;
break;
case 10:
resid = R.drawable.circle_10;
break;
case 11:
resid = R.drawable.circle_11;
break;
case 12:
resid = R.drawable.circle_12;
break;
}
//把歷史的ImageView 圖片對象(image_)釋放
BitmapDrawable bitmapDrawable = (BitmapDrawable)image_.getBackground();
if(bitmapDrawable!=null){
Bitmap hisBitmap = bitmapDrawable.getBitmap();
if(hisBitmap.isRecycled()==false)
{
hisBitmap.recycle();
}
}
//上面的代碼一定要做,否則不會超過30分鐘可定會出現exit,當然我的timer設置的時間比較短。。。。。timer.schedule(task, 5, 5);
//下面代碼是網上通常搜到的源碼例子,但是不能解決,智能優化,只有加上上面的才能徹底解決內存的問題。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true; // bitmap can be purged to disk
options.inInputShareable = true;
Bitmap bm = BitmapFactory.decodeStream(getResources().openRawResource(
resid));
Drawable bd = new BitmapDrawable(getResources(), bm);
image_.setBackgroundDrawable(bd);
}