这几天一直研究在安卓开发中图片应该如何处理,在网上翻了好多资料,这里做点小总结,如果朋友们有更好的解决方案,可以留言一起交流下。
内存缓存技术
在我们开发程序中要在界面上加载一张图片是件非常容易的事情,但如果是加载一堆图片呢?比如ListView,GridView这类的控件,随着屏幕滑动,图片加载也会越来越多,应用程序所可以使用的内存毕竟是有限的,如果一味的去加载图片,很容易导致OOM(Out Of Memory)内存溢出,导致程序崩溃。
这里我们一般的做法是将显示在屏幕之外的图片进行内存回收,此时的垃圾回收器会认为应用对这些图片不再持有引用,从而进行GC操作。但现实还需要考虑到问题是,如果用户又滑动屏幕回到之前我们已经回收掉的图片位置,这时候该怎么办?重新去加载一张图片肯定是不可取的,这样既浪费了时间,又浪费了用户的流量。
这里我们就会想到利用内存缓存来解决这个问题,利用内存缓存可以让应用快速的加载和处理图片,从而提高流畅性。
内存缓存技术对那些大量占用应用程序宝贵内存的图片提供了快速访问的方法,其中最核心的类是LruCache (此类在android-support-v4的包中提供) 。这个类非常适合用来缓存图片,它的主要算法原理是把最近使用的对象用强引用存储在 LinkedHashMap 中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除。
在过去,我们经常会使用一种非常流行的内存缓存技术的实现,即软引用或弱引用 (SoftReference or WeakReference)。但是现在已经不再推荐使用这种方式了,因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。另外,Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存当中,因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃。
对于LruCache类不熟悉的朋友可以看看这篇文章《》。
磁盘缓存技术
对于内存缓存LruCache只是管理了内存中图片的存储与释放,如果图片从内存中被移除的话,那么又需要从网络上重新加载一次图片,这显然非常耗时。对此,Google又提供了一套硬盘缓存的解决方案:DiskLruCache(非Google官方编写,但获得官方认证)。
关于磁盘缓存DisLruCache类不熟悉的朋友可以看看这篇文章的介绍《》
完美结合LruCache+DiskLruCache
首先先来看下实现效果:
这是一个很简单的布局,大布局是GridView,小布局ImageView嵌套在大布局里,贴上代码再做分析吧,其实注释也挺全的。
既然要完成磁盘存储,那么必不可少的就是DisLruCache类的,先引进项目里再说,再来就是图片资源集合了。
图片资源类:
1 package com.example.photoswall; 2 3 4 /** 5 * 图片资源类 6 * @author Balla_兔子 7 * 8 */ 9 public class Images {10 11 public final static String[] imageThumbUrls = new String[] {12 "https://img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg",13 "https://img-my.csdn.net/uploads/201407/26/1406383291_6518.jpg",14 "https://img-my.csdn.net/uploads/201407/26/1406383291_8239.jpg",15 "https://img-my.csdn.net/uploads/201407/26/1406383290_9329.jpg",16 "https://img-my.csdn.net/uploads/201407/26/1406383290_1042.jpg",17 "https://img-my.csdn.net/uploads/201407/26/1406383275_3977.jpg",18 "https://img-my.csdn.net/uploads/201407/26/1406383265_8550.jpg",19 "https://img-my.csdn.net/uploads/201407/26/1406383264_3954.jpg",20 "https://img-my.csdn.net/uploads/201407/26/1406383264_4787.jpg",21 "https://img-my.csdn.net/uploads/201407/26/1406383264_8243.jpg",22 "https://img-my.csdn.net/uploads/201407/26/1406383248_3693.jpg",23 "https://img-my.csdn.net/uploads/201407/26/1406383243_5120.jpg",24 "https://img-my.csdn.net/uploads/201407/26/1406383242_3127.jpg",25 "https://img-my.csdn.net/uploads/201407/26/1406383242_9576.jpg",26 "https://img-my.csdn.net/uploads/201407/26/1406383242_1721.jpg",27 "https://img-my.csdn.net/uploads/201407/26/1406383219_5806.jpg",28 "https://img-my.csdn.net/uploads/201407/26/1406383214_7794.jpg",29 "https://img-my.csdn.net/uploads/201407/26/1406383213_4418.jpg",30 "https://img-my.csdn.net/uploads/201407/26/1406383213_3557.jpg",31 "https://img-my.csdn.net/uploads/201407/26/1406383210_8779.jpg",32 "https://img-my.csdn.net/uploads/201407/26/1406383172_4577.jpg",33 "https://img-my.csdn.net/uploads/201407/26/1406383166_3407.jpg",34 "https://img-my.csdn.net/uploads/201407/26/1406383166_2224.jpg",35 "https://img-my.csdn.net/uploads/201407/26/1406383166_7301.jpg",36 "https://img-my.csdn.net/uploads/201407/26/1406383165_7197.jpg",37 "https://img-my.csdn.net/uploads/201407/26/1406383150_8410.jpg",38 "https://img-my.csdn.net/uploads/201407/26/1406383131_3736.jpg",39 "https://img-my.csdn.net/uploads/201407/26/1406383130_5094.jpg",40 "https://img-my.csdn.net/uploads/201407/26/1406383130_7393.jpg",41 "https://img-my.csdn.net/uploads/201407/26/1406383129_8813.jpg",42 "https://img-my.csdn.net/uploads/201407/26/1406383100_3554.jpg",43 "https://img-my.csdn.net/uploads/201407/26/1406383093_7894.jpg",44 "https://img-my.csdn.net/uploads/201407/26/1406383092_2432.jpg",45 "https://img-my.csdn.net/uploads/201407/26/1406383092_3071.jpg",46 "https://img-my.csdn.net/uploads/201407/26/1406383091_3119.jpg",47 "https://img-my.csdn.net/uploads/201407/26/1406383059_6589.jpg",48 "https://img-my.csdn.net/uploads/201407/26/1406383059_8814.jpg",49 "https://img-my.csdn.net/uploads/201407/26/1406383059_2237.jpg",50 "https://img-my.csdn.net/uploads/201407/26/1406383058_4330.jpg",51 "https://img-my.csdn.net/uploads/201407/26/1406383038_3602.jpg",52 "https://img-my.csdn.net/uploads/201407/26/1406382942_3079.jpg",53 "https://img-my.csdn.net/uploads/201407/26/1406382942_8125.jpg",54 "https://img-my.csdn.net/uploads/201407/26/1406382942_4881.jpg",55 "https://img-my.csdn.net/uploads/201407/26/1406382941_4559.jpg",56 "https://img-my.csdn.net/uploads/201407/26/1406382941_3845.jpg",57 "https://img-my.csdn.net/uploads/201407/26/1406382924_8955.jpg",58 "https://img-my.csdn.net/uploads/201407/26/1406382923_2141.jpg",59 "https://img-my.csdn.net/uploads/201407/26/1406382923_8437.jpg",60 "https://img-my.csdn.net/uploads/201407/26/1406382922_6166.jpg",61 "https://img-my.csdn.net/uploads/201407/26/1406382922_4843.jpg",62 "https://img-my.csdn.net/uploads/201407/26/1406382905_5804.jpg",63 "https://img-my.csdn.net/uploads/201407/26/1406382904_3362.jpg",64 "https://img-my.csdn.net/uploads/201407/26/1406382904_2312.jpg",65 "https://img-my.csdn.net/uploads/201407/26/1406382904_4960.jpg",66 "https://img-my.csdn.net/uploads/201407/26/1406382900_2418.jpg",67 "https://img-my.csdn.net/uploads/201407/26/1406382881_4490.jpg",68 "https://img-my.csdn.net/uploads/201407/26/1406382881_5935.jpg",69 "https://img-my.csdn.net/uploads/201407/26/1406382880_3865.jpg",70 "https://img-my.csdn.net/uploads/201407/26/1406382880_4662.jpg",71 "https://img-my.csdn.net/uploads/201407/26/1406382879_2553.jpg",72 "https://img-my.csdn.net/uploads/201407/26/1406382862_5375.jpg",73 "https://img-my.csdn.net/uploads/201407/26/1406382862_1748.jpg",74 "https://img-my.csdn.net/uploads/201407/26/1406382861_7618.jpg",75 "https://img-my.csdn.net/uploads/201407/26/1406382861_8606.jpg",76 "https://img-my.csdn.net/uploads/201407/26/1406382861_8949.jpg",77 "https://img-my.csdn.net/uploads/201407/26/1406382841_9821.jpg",78 "https://img-my.csdn.net/uploads/201407/26/1406382840_6603.jpg",79 "https://img-my.csdn.net/uploads/201407/26/1406382840_2405.jpg",80 "https://img-my.csdn.net/uploads/201407/26/1406382840_6354.jpg",81 "https://img-my.csdn.net/uploads/201407/26/1406382839_5779.jpg",82 "https://img-my.csdn.net/uploads/201407/26/1406382810_7578.jpg",83 "https://img-my.csdn.net/uploads/201407/26/1406382810_2436.jpg",84 "https://img-my.csdn.net/uploads/201407/26/1406382809_3883.jpg",85 "https://img-my.csdn.net/uploads/201407/26/1406382809_6269.jpg",86 "https://img-my.csdn.net/uploads/201407/26/1406382808_4179.jpg",87 "https://img-my.csdn.net/uploads/201407/26/1406382790_8326.jpg",88 "https://img-my.csdn.net/uploads/201407/26/1406382789_7174.jpg",89 "https://img-my.csdn.net/uploads/201407/26/1406382789_5170.jpg",90 "https://img-my.csdn.net/uploads/201407/26/1406382789_4118.jpg",91 "https://img-my.csdn.net/uploads/201407/26/1406382788_9532.jpg",92 "https://img-my.csdn.net/uploads/201407/26/1406382767_3184.jpg",93 "https://img-my.csdn.net/uploads/201407/26/1406382767_4772.jpg",94 "https://img-my.csdn.net/uploads/201407/26/1406382766_4924.jpg",95 "https://img-my.csdn.net/uploads/201407/26/1406382766_5762.jpg",96 "https://img-my.csdn.net/uploads/201407/26/1406382765_7341.jpg"97 };98 }
DiskLruCache(磁盘缓存类):
1 /* 2 * Copyright (C) 2011 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.example.photoswall; 18 19 import java.io.BufferedInputStream; 20 import java.io.BufferedWriter; 21 import java.io.Closeable; 22 import java.io.EOFException; 23 import java.io.File; 24 import java.io.FileInputStream; 25 import java.io.FileNotFoundException; 26 import java.io.FileOutputStream; 27 import java.io.FileWriter; 28 import java.io.FilterOutputStream; 29 import java.io.IOException; 30 import java.io.InputStream; 31 import java.io.InputStreamReader; 32 import java.io.OutputStream; 33 import java.io.OutputStreamWriter; 34 import java.io.Reader; 35 import java.io.StringWriter; 36 import java.io.Writer; 37 import java.lang.reflect.Array; 38 import java.nio.charset.Charset; 39 import java.util.ArrayList; 40 import java.util.Arrays; 41 import java.util.Iterator; 42 import java.util.LinkedHashMap; 43 import java.util.Map; 44 import java.util.concurrent.Callable; 45 import java.util.concurrent.ExecutorService; 46 import java.util.concurrent.LinkedBlockingQueue; 47 import java.util.concurrent.ThreadPoolExecutor; 48 import java.util.concurrent.TimeUnit; 49 50 /** 51 ****************************************************************************** 52 * Taken from the JB source code, can be found in: 53 * libcore/luni/src/main/java/libcore/io/DiskLruCache.java 54 * or direct link: 55 * https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java 56 ****************************************************************************** 57 * 58 * A cache that uses a bounded amount of space on a filesystem. Each cache 59 * entry has a string key and a fixed number of values. Values are byte 60 * sequences, accessible as streams or files. Each value must be between { @code 61 * 0} and { @code Integer.MAX_VALUE} bytes in length. 62 * 63 *The cache stores its data in a directory on the filesystem. This 64 * directory must be exclusive to the cache; the cache may delete or overwrite 65 * files from its directory. It is an error for multiple processes to use the 66 * same cache directory at the same time. 67 * 68 *
This cache limits the number of bytes that it will store on the 69 * filesystem. When the number of stored bytes exceeds the limit, the cache will 70 * remove entries in the background until the limit is satisfied. The limit is 71 * not strict: the cache may temporarily exceed it while waiting for files to be 72 * deleted. The limit does not include filesystem overhead or the cache 73 * journal so space-sensitive applications should set a conservative limit. 74 * 75 *
Clients call {
@link #edit} to create or update the values of an entry. An 76 * entry may have only one editor at one time; if a value is not available to be 77 * edited then { @link #edit} will return null. 78 *
- 79 *
- When an entry is being created it is necessary to 80 * supply a full set of values; the empty value should be used as a 81 * placeholder if necessary. 82 *
- When an entry is being edited, it is not necessary 83 * to supply data for every value; values default to their previous 84 * value. 85 *
Clients call {
@link #get} to read a snapshot of an entry. The read will 91 * observe the value at the time that { @link #get} was called. Updates and 92 * removals after the call do not impact ongoing reads. 93 * 94 *This class is tolerant of some I/O errors. If files are missing from the 95 * filesystem, the corresponding entries will be dropped from the cache. If 96 * an error occurs while writing a cache value, the edit will fail silently. 97 * Callers should handle other problems by catching {
@code IOException} and 98 * responding appropriately. 99 */100 public final class DiskLruCache implements Closeable {101 static final String JOURNAL_FILE = "journal";102 static final String JOURNAL_FILE_TMP = "journal.tmp";103 static final String MAGIC = "libcore.io.DiskLruCache";104 static final String VERSION_1 = "1";105 static final long ANY_SEQUENCE_NUMBER = -1;106 private static final String CLEAN = "CLEAN";107 private static final String DIRTY = "DIRTY";108 private static final String REMOVE = "REMOVE";109 private static final String READ = "READ";110 111 private static final Charset UTF_8 = Charset.forName("UTF-8");112 private static final int IO_BUFFER_SIZE = 8 * 1024;113 114 /*115 * This cache uses a journal file named "journal". A typical journal file116 * looks like this:117 * libcore.io.DiskLruCache118 * 1119 * 100120 * 2121 *122 * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054123 * DIRTY 335c4c6028171cfddfbaae1a9c313c52124 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342125 * REMOVE 335c4c6028171cfddfbaae1a9c313c52126 * DIRTY 1ab96a171faeeee38496d8b330771a7a127 * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234128 * READ 335c4c6028171cfddfbaae1a9c313c52129 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6130 *131 * The first five lines of the journal form its header. They are the132 * constant string "libcore.io.DiskLruCache", the disk cache's version,133 * the application's version, the value count, and a blank line.134 *135 * Each of the subsequent lines in the file is a record of the state of a136 * cache entry. Each line contains space-separated values: a state, a key,137 * and optional state-specific values.138 * o DIRTY lines track that an entry is actively being created or updated.139 * Every successful DIRTY action should be followed by a CLEAN or REMOVE140 * action. DIRTY lines without a matching CLEAN or REMOVE indicate that141 * temporary files may need to be deleted.142 * o CLEAN lines track a cache entry that has been successfully published143 * and may be read. A publish line is followed by the lengths of each of144 * its values.145 * o READ lines track accesses for LRU.146 * o REMOVE lines track entries that have been deleted.147 *148 * The journal file is appended to as cache operations occur. The journal may149 * occasionally be compacted by dropping redundant lines. A temporary file named150 * "journal.tmp" will be used during compaction; that file should be deleted if151 * it exists when the cache is opened.152 */153 154 private final File directory;155 private final File journalFile;156 private final File journalFileTmp;157 private final int appVersion;158 private final long maxSize;159 private final int valueCount;160 private long size = 0;161 private Writer journalWriter;162 private final LinkedHashMapMD5Utils(MD5转换工具类):
1 package com.example.photoswall; 2 3 import java.math.BigInteger; 4 import java.security.MessageDigest; 5 import java.security.NoSuchAlgorithmException; 6 7 public class MD5Utils { 8 /** 9 * 使用md5的算法进行加密10 */11 public static String md5(String plainText) {12 byte[] secretBytes = null;13 try {14 secretBytes = MessageDigest.getInstance("md5").digest(15 plainText.getBytes());16 } catch (NoSuchAlgorithmException e) {17 throw new RuntimeException("没有md5这个算法!");18 }19 String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字20 // 如果生成数字未满32位,需要前面补021 for (int i = 0; i < 32 - md5code.length(); i++) {22 md5code = "0" + md5code;23 }24 return md5code;25 }26 27 }
上面三个类直接引入项目就行了,接下来说说核心实现代码了。
PhotoWallAdapter(GridView适配器类):
说下思路:由于我们的图片源是单纯的字符串(网址),这里给GridView适配的Adpter采用ArrayAdapter,当然如果你想用BaseAdatper也是可以的,思路不变。
1、继承ArrayAdatper,在构造函数传入必要参数后,需要进行2个操作:1、对内存缓存类的初始化 2、对磁盘缓存的初始化
2、然后在getView方法中来设置图片源,首先先设置成一张默认的图片,然后根据图片的URL去缓存中找是否有相关联的资源,如果没找到在磁盘缓存中找,如果还是没找到再去网络上下载,然后保存在磁盘缓存里,在以上的任一环节(磁盘,网络)里,只要我们找到了相对的图片资源,我们就把它添加到内存缓存中,以便下一次的引用。为了避免异步下载图片造成的图片错位现象,我们在每一个ImageView里设置了一个标识符Tag,Tag为图片的唯一标志:URL地址。
3、由于磁盘缓存属于I/O操作,网络属于下载操作都是属于耗时性的工作,这里我们开启了一个内部类Async异步类去完成,把所有的耗时操作都安排在doInBackground里执行(这里选择Async而不选择直接new Thread的原因是,Async运用了线程池的概念,会比单开子线程会更省资源,而且所有的任务会按照队列的顺序去执行)
由于这里的图片都是比较小的,在实际开发中,大家可以对利用BitmapFactory的Options类对图片进行压缩再展示。
1 package com.example.photoswall; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.IOException; 7 import java.io.OutputStream; 8 import java.net.HttpURLConnection; 9 import java.net.URL; 10 import java.util.HashSet; 11 import java.util.Set; 12 13 import android.content.Context; 14 import android.content.pm.PackageInfo; 15 import android.content.pm.PackageManager.NameNotFoundException; 16 import android.graphics.Bitmap; 17 import android.graphics.BitmapFactory; 18 import android.os.AsyncTask; 19 import android.os.Environment; 20 import android.support.v4.util.LruCache; 21 import android.util.Log; 22 import android.view.LayoutInflater; 23 import android.view.View; 24 import android.view.ViewGroup; 25 import android.widget.ArrayAdapter; 26 import android.widget.GridView; 27 import android.widget.ImageView; 28 29 import com.example.photoswall.DiskLruCache.Snapshot; 30 31 public class PhotoWallAdapter extends ArrayAdapter{ 32 33 // 声明LruCache缓存对象 34 private LruCache lruCache; 35 // 声明DiskLruCache硬盘缓存对象 36 private DiskLruCache diskLruCache; 37 // 任务队列 38 private Set tasks; 39 // 声明GridView对象 40 private GridView gridView; 41 42 public PhotoWallAdapter(Context context, int textViewResourceId, String[] objects, GridView gridView) { 43 super(context, textViewResourceId, objects); 44 this.gridView = gridView; 45 tasks = new HashSet (); 46 /** 47 * 初始化内存缓存LruCache 48 */ 49 // 获取应用程序最大可占内存值 50 int maxMemory = (int) Runtime.getRuntime().maxMemory(); 51 // 设置最大内存的八分之一作为缓存大小 52 int lruMemory = maxMemory / 8; 53 lruCache = new LruCache (lruMemory) { 54 @Override 55 protected int sizeOf(String key, Bitmap bitmap) { 56 // 返回Bitmap对象所占大小,单位:kb 57 return bitmap.getByteCount(); 58 } 59 60 }; 61 /** 62 * 初始化硬盘缓存DiskLruCahce 63 */ 64 // 获取硬盘缓存路径,参数二为所在缓存路径的文件夹名称 65 File directory = getDiskCacheDir(getContext(), "bitmap"); 66 if (!directory.exists()) { 67 // 若文件夹不存在,建立文件夹 68 directory.mkdirs(); 69 } 70 int appVersion = getAppVersion(getContext()); 71 try { 72 // 参数1:缓存文件路径,参数2:系统版本号,参数3:一个缓存路径对于几个文件,参数4:缓存空间大小:字节 73 diskLruCache = DiskLruCache.open(directory, appVersion, 1, 1024 * 1024 * 10); 74 } catch (IOException e) { 75 e.printStackTrace(); 76 } 77 78 } 79 80 /** 81 * @param context 82 * @param uniqueName 83 * @return 84 * 当SD卡存在或者SD卡不可被移除的时候,就调用getExternalCacheDir()方法来获取缓存路径,否则就调用getCacheDir 85 * ()方法来获取缓存路径。 前者获取到的就是 /sdcard/Android/data/ /cache 这个路径 而后者获取到的是 datadata/application package>/cache 87 * 这个路径。 88 */ 89 public File getDiskCacheDir(Context context, String uniqueName) { 90 String cachePath; 91 if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { 92 cachePath = context.getExternalCacheDir().getPath(); 93 } else { 94 cachePath = context.getCacheDir().getPath(); 95 } 96 return new File(cachePath + File.separator + uniqueName); 97 } 98 99 /**100 * @param context101 * @return 获取系统版本号102 */103 public int getAppVersion(Context context) {104 try {105 PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);106 return info.versionCode;107 } catch (NameNotFoundException e) {108 e.printStackTrace();109 }110 return 1;111 }112 113 @Override114 public View getView(int position, View convertView, ViewGroup parent) {115 // 获取图片资源URL地址116 String path = getItem(position);117 View view = null;118 if (convertView == null) {119 view = LayoutInflater.from(getContext()).inflate(R.layout.gridview_item, null);120 } else {121 view = convertView;122 }123 // 获取控件实例124 ImageView imageView = (ImageView) view.findViewById(R.id.iv_photo);125 // 设置一个唯一标识符,避免异步加载图片时错位126 imageView.setTag(path);127 // 设置默认图片128 imageView.setImageResource(R.drawable.ic_launcher);129 // 根据图片URL到缓存中去找图片资源并设置130 setImageFromLruCache(path, imageView);131 return view;132 }133 134 /**135 * 根据图片URL地址获取缓存中图片,若不存在去磁盘缓存中查找=》网络下载136 * 137 * @param path138 * @param imageView139 */140 private void setImageFromLruCache(String path, ImageView imageView) {141 Bitmap bitmap = lruCache.get(path);142 if (bitmap != null) {143 // 缓存存在,取出设置图片144 Log.i("PhotoWallAdapter", "在内存缓存中找到");145 imageView.setImageBitmap(bitmap);146 } else {147 // 缓存不存在,先找硬盘缓存,还不存在,就去网络下载(开启异步任务)148 LoadImageAsync loadImageAsync = new LoadImageAsync();149 loadImageAsync.execute(path);150 // 添加任务到任务队列151 tasks.add(loadImageAsync);152 }153 }154 155 /**156 * 取消队列中准备下载和正在下载的任务157 */158 public void cancelTask() {159 for (LoadImageAsync task : tasks) {160 task.cancel(false);161 }162 }163 164 /**165 * 同步内存操作到journal文件166 */167 public void flushCache() {168 if (diskLruCache != null) {169 try {170 diskLruCache.flush();171 } catch (IOException e) {172 e.printStackTrace();173 }174 }175 176 }177 178 class LoadImageAsync extends AsyncTask {179 // 图片资源URL180 String path = null;181 182 @Override183 protected Bitmap doInBackground(String... params) {184 // 图片下载地址185 this.path = params[0];186 Snapshot snapshot = null;187 OutputStream outputStream = null;188 Bitmap bitmap = null;189 String pathMd5 = MD5Utils.md5(path);190 // 根据图片url(md5)查找图片资源是否存在于硬盘缓存191 try {192 snapshot = diskLruCache.get(pathMd5);193 if (snapshot == null) {194 // 在磁盘缓存中没有找到图片资源195 // 获取一个DiskLruCache写入对象196 DiskLruCache.Editor editor = diskLruCache.edit(pathMd5);197 if (editor != null) {198 outputStream = editor.newOutputStream(0);199 // 开启异步网络任务获取图片,并存入磁盘缓存200 if (downloadUrlToStream(path, outputStream)) {201 // 下载成功202 Log.i("PhotoWallAdapter", "下载文件成功");203 editor.commit();204 } else {205 editor.abort();206 }207 }208 }209 // 图片写入磁盘缓存后,再一次的查找磁盘缓存210 snapshot = diskLruCache.get(pathMd5);211 if (snapshot != null) {212 // 若查找到,获取图片,并把图片资源写入内存缓存213 bitmap = BitmapFactory.decodeStream(snapshot.getInputStream(0));214 Log.i("PhotoWallAdapter", "在磁盘缓存中找到");215 }216 if (bitmap != null) {217 // 将Bitmap对象添加到内存缓存当中218 lruCache.put(path, bitmap);219 }220 return bitmap;221 } catch (IOException e) {222 e.printStackTrace();223 } finally {224 if (outputStream != null) {225 try {226 outputStream.close();227 } catch (IOException e) {228 e.printStackTrace();229 }230 }231 }232 return null;233 }234 235 @Override236 protected void onPostExecute(Bitmap bitmap) {237 super.onPostExecute(bitmap);238 // 根据Tag获取控件对象并设置图片239 ImageView imageView = (ImageView) gridView.findViewWithTag(path);240 if (imageView != null && bitmap != null) {241 // 加载图片242 imageView.setImageBitmap(bitmap);243 }244 tasks.remove(this);245 246 }247 248 /**249 * 根据图片URL地址下载图片,成功返回true,失败false250 * 251 * @param urlString252 * @param outputStream253 * @return254 */255 private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {256 HttpURLConnection urlConnection = null;257 BufferedOutputStream out = null;258 BufferedInputStream in = null;259 try {260 final URL url = new URL(urlString);261 urlConnection = (HttpURLConnection) url.openConnection();262 in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);263 out = new BufferedOutputStream(outputStream, 8 * 1024);264 int b;265 while ((b = in.read()) != -1) {266 out.write(b);267 }268 return true;269 } catch (final IOException e) {270 e.printStackTrace();271 } finally {272 if (urlConnection != null) {273 urlConnection.disconnect();274 }275 try {276 if (out != null) {277 out.close();278 }279 if (in != null) {280 in.close();281 }282 } catch (final IOException e) {283 e.printStackTrace();284 }285 }286 return false;287 }288 289 }290 291 }
MainActivity类:
相比之下这个类就简单许多了,这里需要注意的两点:
1、在onPause方法里进行flush操作(更新磁盘缓存操作日志,磁盘缓存之所以能够被读取取决于日志文件)
2、在Activity销毁之前取消所有正在下载和准备下载的任务。
1 package com.example.photoswall; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.widget.GridView; 6 7 public class MainActivity extends Activity { 8 9 private GridView gv_photo;10 private PhotoWallAdapter adapter;11 12 @Override13 protected void onCreate(Bundle savedInstanceState) {14 super.onCreate(savedInstanceState);15 setContentView(R.layout.activity_main);16 gv_photo = (GridView) findViewById(R.id.gv_photo);17 adapter = new PhotoWallAdapter(MainActivity.this, 0, Images.imageThumbUrls, gv_photo);18 gv_photo.setAdapter(adapter);19 20 }21 22 @Override23 protected void onPause() {24 super.onPause();25 adapter.flushCache();26 }27 28 @Override29 protected void onDestroy() {30 super.onDestroy();31 adapter.cancelTask();32 }33 34 }
剩下的一些细节,代码注释的很详细,还有不清楚的可以看看上文提到附带的2篇文章或者评论给我留言。
作者:
出处:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!