2012-03-11 66 views
0

所以,我使用圖像的自定義數字圖塊。圖像被存儲爲資源。我一直在追蹤內存泄漏,並有理由相信我存儲這些圖像以供使用的方法值得懷疑。目前,我這樣做:存儲短期使用圖像的最佳做法

private void loadImageList() 
{ 
    Log.d(TAG,"Reloading List "+imageList); 
    if (imageList==null || imageList.size()<10) 
    { 
     imageList=new ArrayList<Bitmap>(10); 
     imageList.add(0,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number0)); 
     imageList.add(1,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number1)); 
     imageList.add(2,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number2)); 
     imageList.add(3,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number3)); 
     imageList.add(4,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number4)); 
     imageList.add(5,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number5)); 
     imageList.add(6,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number6)); 
     imageList.add(7,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number7)); 
     imageList.add(8,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number8)); 
     imageList.add(9,BitmapFactory.decodeResource(getResources(), R.drawable.ant_number9)); 
    } 
} 

public void onStart() 
{ 
    super.onStart(); 

    loadImageList(); 

} 

會發生什麼,如果我打開並反覆關閉此應用程序,則系統將不會有足夠的內存來的圖像添加到ImageList。我設置這個按鈕的圖像(當然是用對象ImageButton)。我要補充的是,應用程序有螺紋,並且此調用駐留在runOnUiThread(Runnable)

ImageButton.setImageBitmap(imageList.get(current_var)); 

我試過在onStop()命令刪除圖像,但有時會導致崩潰當線程試圖分配圖像由於野獸的螺紋特性,將其存儲在內存中。

那麼,有沒有更好的方式,我可以加載這些圖像,不會導致內存泄漏?

回答

0

發佈此事後,我意識到一些東西。我可以讓imageList變成靜態的。這些圖像不會從一個視圖變爲另一個視圖。位圖不包含視圖,所以內存不會鎖定。在使用它們之前,我已經檢查過這些值是否存在。而且這個函數被頻繁地使用,以至於保持靜態內存不會影響程序的其他方面。有時它只是幫助把它寫成文字..