2016-12-04 26 views
0

快速的問題,我有多個位圖加載一個頁面上,以節省時間,我將它們保存到內存抓了一段時間後,它被裝在但它應該再充分明確的位圖止損出局內存異常

自動刪除

但如果我不斷重新加載頁面最終會因爲內存不足異常而崩潰,我想清除所有的位圖,包括在catch中的位圖,一旦我重新加載頁面,因爲我不知道當我完成每個位圖 我有5個imageViews,不斷地改變圖像,所以它有點難以跟蹤他們 有沒有辦法做到這一點?

final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024); 
    final int cacheSize = maxMemory/8; 

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { 
     @Override 
     protected int sizeOf(String key, Bitmap bitmap) { 
      // The cache size will be measured in kilobytes rather than 
      // number of items. 
      return bitmap.getByteCount()/1024; 
     } 
    }; 

} 

public void addBitmapToMemoryCache(String key, Bitmap bitmap) { 
    if(getBitmapFromMemCache(key) == null) { 
     mMemoryCache.put(key, bitmap); 
    } 
} 

public Bitmap getBitmapFromMemCache(String key) { 
    return mMemoryCache.get(key); 
} 

public void loadBitmap(String resId, ImageView imageView) { 
    final String imageKey = String.valueOf(resId); 
    iv = imageView.getWidth(); 
    Bitmap bitmap = getBitmapFromMemCache(imageKey); 
    if(bitmap != null) { 
     imageView.setImageBitmap(bitmap); 
    }else{ 
     if(cancelPotentialWork(imageKey, imageView)){ 
      Bitmap loading = decodeSampledBitmapFromResource(ctx.getResources(), R.drawable.whiteseetrough, imageView.getWidth(), imageView.getWidth()); 
      BitmapWorkerTask task = new BitmapWorkerTask(imageView); 
      AsyncDrawable asyncDrawable = new AsyncDrawable(ctx.getResources(), loading, task); 
      imageView.setImageDrawable(asyncDrawable); 
      task.execute(resId); 
     } 
    } 
} 

這裏是我的代碼加載位圖,並添加趕上我把它用

bitmapHTTP getBitmap = new bitmapHTTP(this); 

getBitmap.loadBitmap(picUrl, imageView); 
+0

你對「頁面」有什麼意思?這是一個listView/recyclerView? – Opiatefuchs

回答

0

通話LruCache的這種方法在你的刷新方法

mMemoryCache.evictAll() 
0

首先,你需要在完成使用後調用bitmap.recycle(),只是釋放引用是不夠的。

注意高速緩存中的集合和使用中的集合並不總是相同的(儘管在特定情況下它們可以相同,具體取決於您的使用情況)。如果它們可以分開,則必須將使用的圖像保存在單獨的數據結構中,例如通過維護引用計數和覆蓋LRUCache方法來在適當時跟蹤和回收。

這並不那麼簡單,參見When should I recycle a bitmap using LRUCache?討論和代碼。