圖像緩存是我構建並放入應用商店的應用程序的重要組成部分。該應用程序需要下載圖像並將其緩存在內存和SD卡上,以便其範圍超出一次運行。
總的想法是將圖像添加到緩存管理器中,該緩存管理器既通過基於元數據的密鑰將圖像存儲在關聯容器(HashMap)中,又b)將圖像文件寫入SD卡。
在內存不足的情況下,我釋放HashMap。但仍然可以從SD_Card中檢索圖像,並再次緩存到內存中。
我能夠做到這一點,沒有回收,仍然沒有看到內存問題。據我瞭解,回收並不是必需的,但有助於獲得用於「位圖」的內存的早期版本,因爲在薑餅操作系統前的位圖分配使用本機內存。即不是Dalvik堆的一部分的內存。所以垃圾收集器不釋放這些內存,而是由實現特定的策略釋放。
這是從Cache_Manager類:
public static synchronized void addImage(Bitmap b, String urlString, boolean bSaveToFile, IMAGE_TYPES eIT, boolean bForce)
{
String szKey = getKeyFromUrlString(urlString, eIT);
if (false == m_hmCachedImages.containsKey(szKey) || bForce)
{
m_hmCachedImages.put(szKey, b);
if (bSaveToFile)
{
boolean bIsNull = false;
// Write a null object to disk to prevent future query for non-existent image.
if (null == b)
{
try
{
bIsNull = true;
b = getNullArt();
}
catch (NullPointerException e)
{
e.printStackTrace();
throw e;
}
}
// Don't force null art to disk
if (false == File_Manager.imageExists(szKey) || (bForce && bIsNull == false))
File_Manager.writeImage(b, szKey);
}
}
}
從File_Manager類//這裏writeImage(的實例)
public static void writeImage(Bitmap bmp, String szFileName)
{
checkStorage();
if (false == mExternalStorageWriteable)
{
Log.e("FileMan", "No Writable External Device Available");
return;
}
try
{
// Create dirctory if doesn't exist
String szFilePath = getFilesPath();
boolean exists = (new File(szFilePath)).exists();
if (!exists)
{
new File(szFilePath).mkdirs();
}
// Create file
File file = new File(szFilePath, szFileName);
// Write to file
FileOutputStream os = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, os);
} catch (IOException e)
{
// Unable to create file, likely because
// external storage is
// not currently mounted.
Log.e("FileMan", "Error writing file", e);
} catch (Exception e)
{
e.printStackTrace();
throw e;
}
}
尺寸爲50x50的30-40張圖片不應導致OOME。 也許你加載更大的?如果是這樣,你可以縮小它們。 此外,如果某些圖像從SoftReference中清除,它們不會被使用,所以只需在必要時重新加載它們即可。 –