How to avoid overloading memory with bitmaps?

My application uses bitmap images and every time the user goes to a specific action, when he shows the image a second time, when he stops working.

Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"//Pics/"Image.jpg");

I tried using things like ...

BitmapFactory.Options options = new BitmapFactory.Options();
     options.inTempStorage = new byte[16*1024];

Not sure if to install it either. But that does not help. Once the user leaves this activity, is there no way to clear the bitmap, etc.? thank

+3
source share
3 answers

Call Bitmap.recycle () when you are done using Bitmap to free memory.

+8
source

Bitmap.recycle(), ( , : " ?" ), , :

// 1. create a cache map
private WeakHashMap<String, SoftReference<Bitmap>> mCache;

, - WeakReference SoftReference .

//2. when you need a bitmap, ask for it:
public Bitmap get(String key){
    if( key == null ){
        return null;
    }
    if( mCache.containsKey(key) ){
        SoftReference<Bitmap> reference = mCache.get(key);
        Bitmap bitmap = reference.get();
        if( bitmap != null ){
            return bitmap;
        }
        return decodeFile(key);
    }
    // the key does not exists so it could be that the
    // file is not downloaded or decoded yet...
    File file = new File(Environment.getExternalStorageDirectory(), key);
    if( file.exists() ){
        return decodeFile(key);
    } else{
        throw new RuntimeException("Boooom!");
    }
}

. , ; .

//3. the decode file will look like this in your case
private Bitmap decodeFile(String key) {
    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"//Pics/"+key);
    mCache.put(key, new SoftReference<Bitmap>(bitmap));
    return bitmap;
}

, .

+8

. softreferences, , memrory, outofmemory.

In android, this is not always the case. I had to implement my own caching system for images, and I can assure that objects with soft binding were not deleted from memory when the memory was almost full.

Finally, I had to switch to hard links (regular), but used android.support.v4.util.LruCache to manage cached objects. I would call recycle on onRemoved callback from lru cache. Its definitely more convenient.

Greetings.

+1
source

Source: https://habr.com/ru/post/1790990/


All Articles