0
我有一個位圖hashmap,它提供了適配器視圖所需的圖像展示圖像。Android hashmap clear onTrimMemory does not釋放內存
我的縮略圖大小可能在64x64的dp框內。
但我仍然看到類似heap grown for alloction of 1.xx mb
的日誌。然後,我打印了這個Bytecounts,並驗證了我使用的代碼實際上不會縮略圖。由此產生的位圖大小大多大於兆字節。
我使用的代碼如下
@Override
protected Bitmap doInBackground(Uri... params) {
data = params[0];
// Log.e(TAG,"Async Task Drawable doInBackground");
try {
Bitmap bmp;
if (MainActivity.thumbCache.containsKey(albumId)) {
bmp = (Bitmap) MainActivity.thumbCache.get(albumId);
Log.e("BMWT-HM-Size","getting from Cache"+String.valueOf(MainActivity.thumbCache.size()));
Log.e(TAG,": bmp.getByteCount() "+bmp.getByteCount());
} else {
in = res.openInputStream(data);
songArtOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in,null,songArtOptions);
Log.e(TAG,String.valueOf(songArtOptions.outWidth)+"x"+String.valueOf(songArtOptions.outHeight)+": "+songArtOptions.outMimeType);
songArtOptions.inSampleSize = calculateInSampleSize(songArtOptions,songArtWidth,songArtHeight);
Log.e(TAG,"subSampleLevel = "+String.valueOf(songArtOptions.inSampleSize));
in = res.openInputStream(data);
songArtOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(in,null,songArtOptions);
MainActivity.thumbCache.put(albumId, bmp);
Log.e("BMWT-HM-Size","newly decoded"+String.valueOf(MainActivity.thumbCache.size()));
Log.e(TAG,": bmp.getByteCount() "+bmp.getByteCount());
}
return bmp;
} catch (FileNotFoundException e) {
return defaultArt;
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
int halfHeight = options.outHeight >> 1;
int halfWidth = options.outWidth >> 1;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while (halfWidth > reqWidth && halfHeight > reqHeight) {
inSampleSize <<= 1;
halfWidth >>= 1;
halfHeight >>= 1;
}
}
return inSampleSize;
}
其結果是,我的堆增長儘可能多的圖片被放入HashMap中。
in OnTrimMemory
我打電話給我,thumbCache.clear
,我希望通過hashmap的元素釋放佔用的內存,但事實並非如此。堆狀態保持不變。
如何清理。只要視圖是可見的,並且想要清除緩存(我的意思是釋放佔用的內存以便GC),則視圖被完全銷燬時,我想維護緩存。
你的意思是說,遍歷'thumbCache'映射的每個鍵並調用'recycle'方法? – nmxprime 2014-11-25 09:38:10
是的,如果你想清除thumbCache並且不再使用Bitmaps,你可以做到這一點。 – jobcrazy 2014-11-26 01:00:38