Android hashmap clear onTrimMemory不释放内存

时间:2014-11-25 05:40:46

标签: java android bitmap hashmap android-memory

我有一个Bitmap的hashmap,它为adapterview提供了所需的图像thmbnails。

我的缩略图大小可能在64x64 dp框内。

但我仍然看到像heap grown for alloction of 1.xx mb这样的日志。然后我打印字节数,并验证我使用的代码实际上没有做缩略图。生成的位图大小通常大于兆字节。

我使用的代码如下

@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。

OnTrimMemory我调用thumbCache.clear,我希望通过hashmap的元素释放占用的内存,但事实并非如此。堆状态保持不变。

如何清理它。我希望只要视图可见就要维护缓存,并希望清除缓存(我的意思是释放被占用的内存为GC),视图完全被破坏。

1 个答案:

答案 0 :(得分:0)

如果您确定Bitmap没有其他用途,可以在从缓存中删除内存后调用Bitmap.recycle()来回收内存。

相关问题