使用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()
換句話說:*我在使用位圖時遇到了OOMException,但我試圖很聰明,並沒有提到這個問題,因爲這樣的問題會被標記爲重複* – Selvin
@Syed Raza Mehdi 我想要什麼要知道的是:我可以對那些停止活動的位圖執行哪些操作,例如活動A開始活動B,現在A已停止並且無法看到。在這種情況下,如果A返回,我可以爲A的ImageView設置空位圖並加載位圖。 我是新來的所以對不起我的可憐的英語 – Gerald