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