首先給大家介紹Android使用緩存機制實現文件下載
在下載文件或者在線瀏覽文件時,或者為了保證文件下載的正確性,需要使用緩存機制,常使用SoftReference來實現。
SoftReference的特點是它的一個實例保存對一個Java對象的軟引用,該軟引用的存在不妨礙垃圾收集線程對該Java對象的回收。也就是說,一旦SoftReference保存了對一個Java對象的軟引用后,在垃圾線程對這個Java對象回收前,SoftReference類所提供的get()方法返回Java對象的強引用。另外,一旦垃圾線程回收該Java對象之后,get()方法將返回null。軟引用可以和一個引用隊列(ReferenceQueue)聯合使用,如果軟引用所引用的對象被垃圾回收器回收,Java虛擬機就會把這個軟引用加入到與之關聯的引用隊列中。
一般的緩存策略是:
一級內存緩存、二級文件緩存(數據庫也算作文件緩存)、三級網絡數據
一、網絡下載的緩存策略
關于網絡下載文件(圖片、音頻、視頻)的基本策略:
1.不要直接下載到目標文件,應使用temp文件作中轉,以確保文件的正確性與完整性,流程如下:
a)以網絡目標文件名 A 生成唯一的本地目標文件名 B
b)以本地目標文件名 B 生成唯一的本地臨時文件名 T
c)下載文件到 T 中
d)下載完畢,校驗文件 T 的正確性與完整性
e)若不正確或不完整則 delete 文件 T,并返回 false
f)校驗完畢后,將文件 T 重命名 或 復制到 B 文件
g)最后的清理現場,刪除臨時文件 T,成功后,返回 true
2.盡力提供文件正確性與完整性的校驗:
a)正確性:比如 MD5/Hash Code 比對、文件格式的比對。
b)完整性:比如 文件大小是否一致、圖片的數據是否正確(圖片文件頭中提供了相關信息)
3.考慮對于下載到本地的文件是否需要再做二次加工,可以思考以下情況:
a)比如網絡源始圖片的大小為800*600,而我們需要作為縮略圖的大小為160*145,所以考慮對下載后的文件進行裁剪,再保存,對于源始文件則直接刪除。
二、文件緩存策略:
1.需要唯一的緩存文件的對應I/O key,一般可以使用 hashcode。
2.若是同一個文件,以不同的時間,可以考慮,先清本地緩存,再下載新的緩存到本地。
3.同一文件也可以加上時間戳后,再生成唯一hashcode。
4.生成文件緩時,也許需要作以下全面的考慮:
a)sdcard是否已經沒有空間(這個需求是存在的,但幾乎沒有人會考慮到,一旦發生,必crash)。
b)緩存的清理策略。每日、每周定時清理?到達一個閥值后,自動清理?(若無清理策略,把垃圾數據一直當個寶一相存著,
是很SB的)。
c)緩存真正需要的數據。不要覺外存是無限的,所以就可以什么都存,要知道,多則繁,繁則亂。曾經有一同事,每天存幾百MB的用戶數據(所有用戶的性別、 age、聯系方式等等),而PM需要的只是一個每日數戶的活躍數據報表,于是最后改為緩存每天的用戶分析報表數據即可(才10幾KB)。
d)給緩存文件加密。最簡單就是去掉文件的擴展名,這也算加密,當然,你可以把服務端文件加密,然后在內存中解密。這就看項目的需求而定,我的經驗也不足,一般就是改改擴展名之類的。
下面給大家介紹Android 異步請求圖片加三級緩存
使用xUtils等框架是很方便,但今天要用代碼實現bitmapUtils 的功能,很簡單,
1 AsyncTask請求一張圖片
####AsyncTask
#####AsyncTask是線程池+handler的封裝 第一個泛型: 傳參的參數類型類型(和doInBackground一致) 第二個泛型:
#####更新進度的參數類型(和onProgressUpdate一致) 第三個泛型: 返回結果的參數類型(和onPostExecute一致,
#####和doInBackground返回類型一致)
看AsyncTask源碼:
public abstract class AsyncTask<Params, Progress, Result> {private static final String LOG_TAG = "AsyncTask";private static final int CORE_POOL_SIZE = 5;private static final int MAXIMUM_POOL_SIZE = 128;private static final int KEEP_ALIVE = 1;private static final ThreadFactory sThreadFactory = new ThreadFactory() {private final AtomicInteger mCount = new AtomicInteger(1);public Thread newThread(Runnable r) {return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());}}; 核心線程5 最大線程128 這是AsyncTask的線程池 然后通過handler發送消息 , 它內部實例化了一個靜態的自定義類 InternalHandler,這個類是繼承自 Handler 的,在這個自定義類中綁定了一個叫做 AsyncTaskResult 的對象,每次子線程需要通知主線程,就調用 sendToTarget 發送消息給 handler自己。然后在 handler 的 handleMessage 中 AsyncTaskResult 根據消息的類型不同(例如 MESSAGE_POST_PROGRESS 會更新進度條,MESSAGE_POST_CANCEL 取消任務)而做不同的操作,值得一提的是,這些操作都是在UI線程進行的,意味著,從子線程一旦需要和 UI 線程交互,內部自動調用了 handler 對象把消息放在了主線程了。
private static final InternalHandler sHandler = new InternalHandler(); mFuture = new FutureTask<Result>(mWorker) {@Overrideprotected void More ...done() {Message message;Result result = null;try {result = get();} catch (InterruptedException e) {android.util.Log.w(LOG_TAG, e);} catch (ExecutionException e) {throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());} catch (CancellationException e) {message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));message.sendToTarget();return;} catch (Throwable t) {throw new RuntimeException("An error occured while executing "+ "doInBackground()", t);}message = sHandler.obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskResult<Result>(AsyncTask.this, result));message.sendToTarget();}};private static class InternalHandler extends Handler {@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})@Overridepublic void More ...handleMessage(Message msg) {AsyncTaskResult result = (AsyncTaskResult) msg.obj;switch (msg.what) {case MESSAGE_POST_RESULT:// There is only one resultresult.mTask.finish(result.mData[0]);break;case MESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate(result.mData);break;case MESSAGE_POST_CANCEL:result.mTask.onCancelled();break;}}}下面看代碼 第一步我們先請求一張圖片 并解析 注釋寫的很詳細了.
NetCacheUtils.java
import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.widget.ImageView;/*** 網絡緩存* * @author Ace* @date 2016-02-18*/public class NetCacheUtils {private LocalCacheUtils mLocalUtils;private MemoryCacheUtils mMemoryUtils;public NetCacheUtils(LocalCacheUtils localUtils,MemoryCacheUtils memoryUtils) {mLocalUtils = localUtils;mMemoryUtils = memoryUtils;}public void getBitmapFromNet(ImageView imageView, String url) {BitmapTask task = new BitmapTask();task.execute(imageView, url);}/*** AsyncTask是線程池+handler的封裝 第一個泛型: 傳參的參數類型類型(和doInBackground一致) 第二個泛型:* 更新進度的參數類型(和onProgressUpdate一致) 第三個泛型: 返回結果的參數類型(和onPostExecute一致,* 和doInBackground返回類型一致)*/class BitmapTask extends AsyncTask<Object, Integer, Bitmap> {private ImageView mImageView;private String url;// 主線程運行, 預加載@Overrideprotected void onPreExecute() {super.onPreExecute();}// 子線程運行, 異步加載邏輯在此方法中處理@Overrideprotected Bitmap doInBackground(Object... params) {mImageView = (ImageView) params[0];url = (String) params[1];mImageView.setTag(url);// 將imageView和url綁定在一起// publishProgress(values)//通知進度// 下載圖片return download(url);}// 主線程運行, 更新進度@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);}// 主線程運行, 更新主界面@Overrideprotected void onPostExecute(Bitmap result) {if (result != null) {// 判斷當前圖片是否就是imageView要的圖片, 防止listview重用導致的圖片錯亂的情況出現String bindUrl = (String) mImageView.getTag();if (bindUrl.equals(url)) {// 給imageView設置圖片mImageView.setImageBitmap(result);// 將圖片保存在本地mLocalUtils.setBitmapToLocal(result, url);// 將圖片保存在內存mMemoryUtils.setBitmapToMemory(url, result);}}}}/*** 下載圖片* * @param url*/public Bitmap download(String url) {HttpURLConnection conn = null;try {conn = (HttpURLConnection) (new URL(url).openConnection());conn.setConnectTimeout(5000);conn.setReadTimeout(5000);conn.setRequestMethod("GET");conn.connect();int responseCode = conn.getResponseCode();if (responseCode == 200) {InputStream in = conn.getInputStream();// 將流轉化為bitmap對象Bitmap bitmap = BitmapFactory.decodeStream(in);return bitmap;}} catch (Exception e) {e.printStackTrace();} finally {if (conn != null) {conn.disconnect();}}return null;}}MemoryCacheUtils.java 用到了LruCache 很簡單我簡單翻譯下文檔:
* A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may * become eligible for garbage collection. * Cache保存一個強引用來限制內容數量,每當Item被訪問的時候,此Item就會移動到隊列的頭部。* 當cache已滿的時候加入新的item時,在隊列尾部的item會被回收。 * <p>If your cached values hold resources that need to be explicitly released, * override {@link #entryRemoved}. * 如果你cache的某個值需要明確釋放,重寫entryRemoved()* <p>By default, the cache size is measured in the number of entries. Override * {@link #sizeOf} to size the cache in different units. For example, this cache * is limited to 4MiB of bitmaps: 默認cache大小是測量的item的數量,重寫sizeof計算不同item的* 大小。 {@code * int cacheSize = 4 * 1024 * 1024; // 4MiB * LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { * protected int sizeOf(String key, Bitmap value) { * return value.getByteCount(); * } * }}-------------------------------------------------------------------<p>This class is thread-safe. Perform multiple cache operations atomically by * synchronizing on the cache: <pre> {@code * synchronized (cache) { * if (cache.get(key) == null) { * cache.put(key, value); * } * }}</pre> * 他是線程安全的,自動地執行多個緩存操作并且加鎖-------------------------<p>This class does not allow null to be used as a key or value. A return * value of null from {@link #get}, {@link #put} or {@link #remove} is * unambiguous: the key was not in the cache.* 不允許key或者value為null* 當get(),put(),remove()返回值為null時,key相應的項不在cache中最重要的大概就是以上幾點: 使用很簡單來看代碼
import android.graphics.Bitmap;import android.support.v4.util.LruCache;/*** 內存緩存工具類* * @author Ace* @date 2016-02-19*/public class MemoryCacheUtils {// Android 2.3 (API Level// 9)開始,垃圾回收器會更傾向于回收持有軟引用或弱引用的對象,這讓軟引用和弱引用變得不再可靠,建議用LruCache,它是強引用private LruCache<String, Bitmap> mCache;public MemoryCacheUtils() {int maxMemory = (int) Runtime.getRuntime().maxMemory();// 獲取虛擬機分配的最大內存// 16M// LRU 最近最少使用, 通過控制內存不要超過最大值(由開發者指定), 來解決內存溢出,就像上面翻譯的所說 如果cache滿了會清理最近最少使用的緩存對象mCache = new LruCache<String, Bitmap>(maxMemory / 8) {@Overrideprotected int sizeOf(String key, Bitmap value) {// 計算一個bitmap的大小int size = value.getRowBytes() * value.getHeight();// 每一行的字節數乘以高度return size;}};}public Bitmap getBitmapFromMemory(String url) {return mCache.get(url);}public void setBitmapToMemory(String url, Bitmap bitmap) {mCache.put(url, bitmap);}}最后一級緩存 本地緩存 把網絡下載的圖片 文件名以MD5的形式保存到內存卡的制定目錄
/*** 本地緩存工具類* * @author Ace* @date 2016-02-19*/public class LocalCacheUtils {// 圖片緩存的文件夾public static final String DIR_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/ace_bitmap_cache";public Bitmap getBitmapFromLocal(String url) {try {File file = new File(DIR_PATH, MD5Encoder.encode(url));if (file.exists()) {Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));return bitmap;}} catch (Exception e) {e.printStackTrace();}return null;}public void setBitmapToLocal(Bitmap bitmap, String url) {File dirFile = new File(DIR_PATH);// 創建文件夾 文件夾不存在或者它不是文件夾 則創建一個文件夾.mkdirs,mkdir的區別在于假如文件夾有好幾層路徑的話,前者會創建缺失的父目錄 后者不會創建這些父目錄if (!dirFile.exists() || !dirFile.isDirectory()) {dirFile.mkdirs();}try {File file = new File(DIR_PATH, MD5Encoder.encode(url));// 將圖片壓縮保存在本地,參1:壓縮格式;參2:壓縮質量(0-100);參3:輸出流bitmap.compress(CompressFormat.JPEG, 100,new FileOutputStream(file));} catch (Exception e) {e.printStackTrace();}}}MD5Encoder
import java.security.MessageDigest;public class MD5Encoder {public static String encode(String string) throws Exception {byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));StringBuilder hex = new StringBuilder(hash.length * 2);for (byte b : hash) {if ((b & 0xFF) < 0x10) {hex.append("0");}hex.append(Integer.toHexString(b & 0xFF));}return hex.toString();}}最后新建一個工具類來使用我們上面的三個緩存工具類
/*** 三級緩存工具類* * @author Ace* @date 2016-02-19*/public class MyBitmapUtils {// 網絡緩存工具類private NetCacheUtils mNetUtils;// 本地緩存工具類private LocalCacheUtils mLocalUtils;// 內存緩存工具類private MemoryCacheUtils mMemoryUtils;public MyBitmapUtils() {mMemoryUtils = new MemoryCacheUtils();mLocalUtils = new LocalCacheUtils();mNetUtils = new NetCacheUtils(mLocalUtils, mMemoryUtils);}public void display(ImageView imageView, String url) {// 設置默認加載圖片imageView.setImageResource(R.drawable.news_pic_default);// 先從內存緩存加載Bitmap bitmap = mMemoryUtils.getBitmapFromMemory(url);if (bitmap != null) {imageView.setImageBitmap(bitmap);System.out.println("從內存讀取圖片啦...");return;}// 再從本地緩存加載bitmap = mLocalUtils.getBitmapFromLocal(url);if (bitmap != null) {imageView.setImageBitmap(bitmap);System.out.println("從本地讀取圖片啦...");// 給內存設置圖片mMemoryUtils.setBitmapToMemory(url, bitmap);return;}// 從網絡緩存加載mNetUtils.getBitmapFromNet(imageView, url);}}以上所述給大家介紹了Android 異步請求圖片加三級緩存的相關知識,希望對大家有所幫助。
新聞熱點
疑難解答
圖片精選