class ImageManager { private HashMap<Integer, Bitmap> mBitmaps; private HashMap<Integer, Drawable> mDrawables; private boolean mActive = true; public ImageManager() { mBitmaps = new HashMap<Integer, Bitmap>(); mDrawables = new HashMap<Integer, Drawable>(); } // We need to share and cache resources between objects to save on memory. public Bitmap getBitmap(int resource) { if (mActive) { if (!mBitmaps.containsKey(resource)) { mBitmaps.put(resource, BitmapFactory.decodeResource(MainActivity.getContext().getResources(), resource)); } return mBitmaps.get(resource); } return null; } public Drawable getDrawable(int resource) { if (mActive) { if (!mDrawables.containsKey(resource)) { mDrawables.put(resource, mGame.getView().getResources().getDrawable(resource)); } return mDrawables.get(resource); } return null; } public void recycleBitmaps() { Iterator itr = mBitmaps.entrySet().iterator(); while (itr.hasNext()) { Map.Entry e = (Map.Entry)itr.next(); ((Bitmap) e.getValue()).recycle(); } mBitmaps.clear(); } public ImageManager setActive(boolean b) { mActive = b; return this; } public boolean isActive() { return mActive; } }
http://blog.pseudoblue.com/2010/08/15/android-bitmaps-and-memory-leaks/