1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.pump.util;
18 
19 import android.graphics.Bitmap;
20 import android.net.Uri;
21 
22 import androidx.annotation.AnyThread;
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.collection.LruCache;
26 import androidx.core.graphics.BitmapCompat;
27 
28 @AnyThread
29 class BitmapCache {
30     private static final int CACHE_SIZE =
31             (int) Math.min(Runtime.getRuntime().maxMemory() / 8, Integer.MAX_VALUE / 4);
32 
33     private final MemoryCache mMemoryCache = new MemoryCache(CACHE_SIZE);
34 
put(@onNull Uri key, @NonNull Bitmap bitmap)35     void put(@NonNull Uri key, @NonNull Bitmap bitmap) {
36         mMemoryCache.put(key, bitmap);
37     }
38 
get(@onNull Uri key)39     @Nullable Bitmap get(@NonNull Uri key) {
40         return mMemoryCache.get(key);
41     }
42 
clear()43     void clear() {
44         mMemoryCache.evictAll();
45     }
46 
47     private static class MemoryCache extends LruCache<Uri, Bitmap> {
MemoryCache(int maxSize)48         private MemoryCache(int maxSize) {
49             super(maxSize);
50         }
51 
52         @Override
sizeOf(@onNull Uri key, @NonNull Bitmap bitmap)53         protected int sizeOf(@NonNull Uri key, @NonNull Bitmap bitmap) {
54             return BitmapCompat.getAllocationByteCount(bitmap);
55         }
56     }
57 }
58