LruCache bitmap caching

Lrucache is the image cache built into the sd card, set the cache capacity is allocated one-eighth of the capacity of the system, the unit byte, cache capacity than gc will automatically recover the cache is not long in use. Lrucache feel the same on the first map, add key on the line, more convenient, and now not to use the official soft reference cache softpreference, it seems to be easy memory leaks

public class MainActivity extends AppCompatActivity {
    private LruCache<String, Bitmap> lruCache;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = findViewById(R.id.image);
        long maxMemory = Runtime.getRuntime().maxMemory();
        int cacheSize = (int) (maxMemory / 8);
        lruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }

        };
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon12);
        lruCache.put("a", bitmap);
        Bitmap bitmap2 = lruCache.get("a");
        if (bitmap2 == null) {
            System.out.println("无缓存");
        } else {
            imageView.setImageBitmap(bitmap2);
        }
    }
}

Because it is the presence of internal storage so without obtaining permission external storage, the output is not on the no-cache cache, you can put into a second try on the output b unbuffered

Guess you like

Origin www.cnblogs.com/Ocean123123/p/10980691.html