2015-06-09 11 views
-3

我買了我的應用程序的一個問題:在我的應用程序,每一個activity有幾個ImageViews,每個ImageViewbitmap組到它。如果打開許多activities recursively分配的內存將保持增長,和終於MemoryCache已滿,所以我不能顯示任何位圖,否則應用程序將crash打開許多活動與位圖遞歸

我該怎麼辦ImageViewactivity已停止?我可以recycle它的bitmap,並重新加載位圖後,其活動恢復?我使用壁畫來處理位圖加載和緩存。

+0

換句話說:*我在使用位圖時遇到了OOMException,但我試圖很聰明,並沒有提到這個問題,因爲這樣的問題會被標記爲重複* – Selvin

+0

@Syed Raza Mehdi 我想要什麼要知道的是:我可以對那些停止活動的位圖執行哪些操作,例如活動A開始活動B,現在A已停止並且無法看到。在這種情況下,如果A返回,我可以爲A的ImageView設置空位圖並加載位圖。 我是新來的所以對不起我的可憐的英語 – Gerald

回答

0

使用Bitmap對象時處理內存的最佳方式是使用LruCache並將您的Bitmap存儲在裏面。 一旦你不再需要你的Bitmap了,你可以存儲到你的緩存並回收它以釋放盡可能多的內存。如果將它存儲到緩存中,則只需從緩存中獲取圖像。

這是我的課HANDELING我的緩存:

public class ImagesCache { 
private LruCache <String, Bitmap> imagesWarehouse; 
private static ImagesCache cache; 

public static ImagesCache getInstance() { 
    if(cache == null) 
     cache = new ImagesCache(); 
    return cache; 
} 

public void initializeCache() { 
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024); 
    final int cacheSize = maxMemory/8; 

    imagesWarehouse = new LruCache<String, Bitmap>(cacheSize) { 
     protected int sizeOf(String key, Bitmap value) { 
      // The cache size will be measured in kilobytes rather than number of items. 
      int bitmapByteCount = value.getRowBytes() * value.getHeight(); 

      return bitmapByteCount/1024; 
     }}; 
} 

public void addImageToWarehouse(String key, Bitmap value) {  
    if (imagesWarehouse != null && imagesWarehouse.get(key) == null) 
     imagesWarehouse.put(key, value); 
} 

public Bitmap getImageFromWarehouse(String key) { 
    if (key != null) 
     return imagesWarehouse.get(key); 
    else 
     return null; 
} 

public void removeImageFromWarehouse(String key) { 
    imagesWarehouse.remove(key); 
} 

public void clearCache() { 
    if (imagesWarehouse != null) 
     imagesWarehouse.evictAll(); 
} 

}

記住,當你的應用程序啓動

cache.initializeCache() 

和清楚,如果當你的應用程序完成

初始化緩存
cache.clearCache() 
+0

我正在使用[Fresco](https://github.com/facebook/fresco)來完成這項工作。而我的問題是:如何處理這些位圖活動停止(例如其活動開始另一活動) – Gerald