LruResourceCache.java revision 98389d828138621d8de3fcf2d819b5a0ae6dc283
1package com.bumptech.glide.load.engine.cache;
2
3import android.annotation.SuppressLint;
4import com.bumptech.glide.load.Key;
5import com.bumptech.glide.load.engine.Resource;
6import com.bumptech.glide.util.LruCache;
7
8/**
9 * An LRU in memory cache for {@link com.bumptech.glide.load.engine.Resource}s.
10 */
11public class LruResourceCache extends LruCache<Key, Resource<?>> implements MemoryCache {
12    private ResourceRemovedListener listener;
13
14    /**
15     * Constructor for LruResourceCache.
16     *
17     * @param size The maximum size in bytes the in memory cache can use.
18     */
19    public LruResourceCache(int size) {
20        super(size);
21    }
22
23    @Override
24    public void setResourceRemovedListener(ResourceRemovedListener listener) {
25        this.listener = listener;
26    }
27
28    @Override
29    protected void onItemEvicted(Key key, Resource<?> item) {
30        if (listener != null) {
31            listener.onResourceRemoved(item);
32        }
33    }
34
35    @Override
36    protected int getSize(Resource<?> item) {
37        return item.getSize();
38    }
39
40    @SuppressLint("InlinedApi")
41    @Override
42    public void trimMemory(int level) {
43        if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
44            // Nearing middle of list of cached background apps
45            // Evict our entire bitmap cache
46            clearMemory();
47        } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) {
48            // Entering list of cached background apps
49            // Evict oldest half of our bitmap cache
50            trimToSize(getCurrentSize() / 2);
51        }
52    }
53}
54