1/* 2 * Copyright (C) 2014 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 17package com.example.android.supportv7.graphics; 18 19import android.graphics.Bitmap; 20import android.os.AsyncTask; 21import android.provider.MediaStore; 22import android.support.v4.graphics.BitmapCompat; 23import android.support.v4.util.LruCache; 24import android.widget.ImageView; 25 26/** 27 * A very naive lazily implemented image loader. Do not use this in production code. 28 */ 29class ImageLoader { 30 31 /** 32 * A LruCache used to store images which has a maximum size of 10% of the maximum heap size. 33 */ 34 private static final BitmapCache CACHE = new BitmapCache( 35 Math.round(Runtime.getRuntime().maxMemory() / 10)); 36 37 private ImageLoader() { 38 } 39 40 interface Listener { 41 void onImageLoaded(Bitmap bitmap); 42 } 43 44 static void loadMediaStoreThumbnail(final ImageView imageView, 45 final long id, 46 final Listener listener) { 47 48 final Bitmap cachedValue = CACHE.get(id); 49 if (cachedValue != null) { 50 // If the image is already in the cache, display the image, 51 // call the listener now and return 52 imageView.setImageBitmap(cachedValue); 53 if (listener != null) { 54 listener.onImageLoaded(cachedValue); 55 } 56 return; 57 } 58 59 new AsyncTask<Void, Void, Bitmap>() { 60 @Override 61 protected Bitmap doInBackground(Void... params) { 62 return MediaStore.Images.Thumbnails.getThumbnail( 63 imageView.getContext().getContentResolver(), 64 id, 65 MediaStore.Images.Thumbnails.MINI_KIND, 66 null); 67 } 68 69 @Override 70 protected void onPostExecute(Bitmap bitmap) { 71 imageView.setImageBitmap(bitmap); 72 73 if (bitmap != null) { 74 // Add the image to the memory cache first 75 CACHE.put(id, bitmap); 76 77 if (listener != null) { 78 listener.onImageLoaded(bitmap); 79 } 80 } 81 } 82 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 83 } 84 85 /** 86 * A simple cache implementation for {@link android.graphics.Bitmap} instances which uses 87 * {@link android.support.v4.util.LruCache}. 88 */ 89 private static class BitmapCache extends LruCache<Long, Bitmap> { 90 BitmapCache(int maxSize) { 91 super(maxSize); 92 } 93 94 @Override 95 protected int sizeOf(Long key, Bitmap value) { 96 return BitmapCompat.getAllocationByteCount(value); 97 } 98 } 99 100} 101