1 /**
2  * Copyright (C) 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.car.radio.platform;
18 
19 import android.graphics.Bitmap;
20 
21 import androidx.annotation.NonNull;
22 import androidx.annotation.Nullable;
23 
24 import com.android.car.broadcastradio.support.platform.ImageResolver;
25 
26 import java.util.LinkedHashMap;
27 import java.util.Map;
28 import java.util.Objects;
29 
30 public class ImageMemoryCache implements ImageResolver {
31     private final RadioManagerExt mRadioManager;
32     private final Map<Long, Bitmap> mCache;
33 
ImageMemoryCache(@onNull RadioManagerExt radioManager, int cacheSize)34     public ImageMemoryCache(@NonNull RadioManagerExt radioManager, int cacheSize) {
35         mRadioManager = Objects.requireNonNull(radioManager);
36         mCache = new CacheMap<>(cacheSize);
37     }
38 
resolve(long globalId)39     public @Nullable Bitmap resolve(long globalId) {
40         synchronized (mCache) {
41             if (mCache.containsKey(globalId)) return mCache.get(globalId);
42 
43             Bitmap bm = mRadioManager.getMetadataImage(globalId);
44             mCache.put(globalId, bm);
45             return bm;
46         }
47     }
48 
49     private static class CacheMap<K, V> extends LinkedHashMap<K, V> {
50         private final int mMaxSize;
51 
CacheMap(int maxSize)52         public CacheMap(int maxSize) {
53             if (maxSize < 0) throw new IllegalArgumentException("maxSize must not be negative");
54             mMaxSize = maxSize;
55         }
56 
57         @Override
removeEldestEntry(Map.Entry<K, V> eldest)58         protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
59             return size() > mMaxSize;
60         }
61     }
62 }
63