1 /*
2  * Copyright (C) 2015 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 package com.android.messaging.datamodel.media;
17 
18 import android.util.SparseArray;
19 
20 import com.android.messaging.Factory;
21 import com.android.messaging.datamodel.MemoryCacheManager;
22 import com.android.messaging.datamodel.MemoryCacheManager.MemoryCache;
23 import com.android.messaging.datamodel.media.PoolableImageCache.ReusableImageResourcePool;
24 
25 /**
26  * Manages a set of media caches by id.
27  */
28 public abstract class MediaCacheManager implements MemoryCache {
get()29     public static MediaCacheManager get() {
30         return Factory.get().getMediaCacheManager();
31     }
32 
33     protected final SparseArray<MediaCache<?>> mCaches;
34 
MediaCacheManager()35     public MediaCacheManager() {
36         mCaches = new SparseArray<MediaCache<?>>();
37         MemoryCacheManager.get().registerMemoryCache(this);
38     }
39 
40     @Override
reclaim()41     public void reclaim() {
42         final int count = mCaches.size();
43         for (int i = 0; i < count; i++) {
44             mCaches.valueAt(i).destroy();
45         }
46         mCaches.clear();
47     }
48 
getOrCreateMediaCacheById(final int id)49     public synchronized MediaCache<?> getOrCreateMediaCacheById(final int id) {
50         MediaCache<?> cache = mCaches.get(id);
51         if (cache == null) {
52             cache = createMediaCacheById(id);
53             if (cache != null) {
54                 mCaches.put(id, cache);
55             }
56         }
57         return cache;
58     }
59 
getOrCreateBitmapPoolForCache(final int cacheId)60     public ReusableImageResourcePool getOrCreateBitmapPoolForCache(final int cacheId) {
61         final MediaCache<?> cache = getOrCreateMediaCacheById(cacheId);
62         if (cache != null && cache instanceof PoolableImageCache) {
63             return ((PoolableImageCache) cache).asReusableBitmapPool();
64         }
65         return null;
66     }
67 
createMediaCacheById(final int id)68     protected abstract MediaCache<?> createMediaCacheById(final int id);
69 }