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