Android實(shí)現(xiàn)圖片異步請求加三級緩存
使用xUtils等框架是很方便,但今天要用代碼實(shí)現(xiàn)bitmapUtils 的功能,很簡單,
AsyncTask請求一張圖片
####AsyncTask
#####AsyncTask是線程池+handler的封裝 第一個泛型: 傳參的參數(shù)類型類型(和doInBackground一致) 第二個泛型:
#####更新進(jìn)度的參數(shù)類型(和onProgressUpdate一致) 第三個泛型: 返回結(jié)果的參數(shù)類型(和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發(fā)送消息 , 它內(nèi)部實(shí)例化了一個靜態(tài)的自定義類 InternalHandler,這個類是繼承自 Handler 的,在這個自定義類中綁定了一個叫做 AsyncTaskResult 的對象,每次子線程需要通知主線程,就調(diào)用 sendToTarget 發(fā)送消息給 handler自己。然后在 handler 的 handleMessage 中 AsyncTaskResult 根據(jù)消息的類型不同(例如 MESSAGE_POST_PROGRESS 會更新進(jìn)度條,MESSAGE_POST_CANCEL 取消任務(wù))而做不同的操作,值得一提的是,這些操作都是在UI線程進(jìn)行的,意味著,從子線程一旦需要和 UI 線程交互,內(nèi)部自動調(diào)用了 handler 對象把消息放在了主線程了。
private static final InternalHandler sHandler = new InternalHandler(); mFuture = new FutureTask<Result>(mWorker) { @Override protected 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"}) @Override public void More ...handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; case MESSAGE_POST_CANCEL: result.mTask.onCancelled(); break; } } }
下面看代碼 第一步我們先請求一張圖片 并解析 注釋寫的很詳細(xì)了.
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; /** * 網(wǎng)絡(luò)緩存 * * @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的封裝 第一個泛型: 傳參的參數(shù)類型類型(和doInBackground一致) 第二個泛型: * 更新進(jìn)度的參數(shù)類型(和onProgressUpdate一致) 第三個泛型: 返回結(jié)果的參數(shù)類型(和onPostExecute一致, * 和doInBackground返回類型一致) */ class BitmapTask extends AsyncTask<Object, Integer, Bitmap> { private ImageView mImageView; private String url; // 主線程運(yùn)行, 預(yù)加載 @Override protected void onPreExecute() { super.onPreExecute(); } // 子線程運(yùn)行, 異步加載邏輯在此方法中處理 @Override protected Bitmap doInBackground(Object... params) { mImageView = (ImageView) params[0]; url = (String) params[1]; mImageView.setTag(url);// 將imageView和url綁定在一起 // publishProgress(values)//通知進(jìn)度 // 下載圖片 return download(url); } // 主線程運(yùn)行, 更新進(jìn)度 @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } // 主線程運(yùn)行, 更新主界面 @Override protected void onPostExecute(Bitmap result) { if (result != null) { // 判斷當(dāng)前圖片是否就是imageView要的圖片, 防止listview重用導(dǎo)致的圖片錯亂的情況出現(xiàn) String bindUrl = (String) mImageView.getTag(); if (bindUrl.equals(url)) { // 給imageView設(shè)置圖片 mImageView.setImageBitmap(result); // 將圖片保存在本地 mLocalUtils.setBitmapToLocal(result, url); // 將圖片保存在內(nèi)存 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(); // 將流轉(zhuǎn)化為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保存一個強(qiáng)引用來限制內(nèi)容數(shù)量,每當(dāng)Item被訪問的時候,此Item就會移動到隊(duì)列的頭部。 * 當(dāng)cache已滿的時候加入新的item時,在隊(duì)列尾部的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: 默認(rèn)cache大小是測量的item的數(shù)量,重寫sizeof計(jì)算不同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> * 他是線程安全的,自動地執(zhí)行多個緩存操作并且加鎖 ------------------------- <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 * 當(dāng)get(),put(),remove()返回值為null時,key相應(yīng)的項(xiàng)不在cache中
最重要的大概就是以上幾點(diǎn): 使用很簡單
來看代碼:
import android.graphics.Bitmap; import android.support.v4.util.LruCache; /** * 內(nèi)存緩存工具類 * * @author Ace * @date 2016-02-19 */ public class MemoryCacheUtils { // Android 2.3 (API Level // 9)開始,垃圾回收器會更傾向于回收持有軟引用或弱引用的對象,這讓軟引用和弱引用變得不再可靠,建議用LruCache,它是強(qiáng)引用 private LruCache<String, Bitmap> mCache; public MemoryCacheUtils() { int maxMemory = (int) Runtime.getRuntime().maxMemory();// 獲取虛擬機(jī)分配的最大內(nèi)存 // 16M // LRU 最近最少使用, 通過控制內(nèi)存不要超過最大值(由開發(fā)者指定), 來解決內(nèi)存溢出,就像上面翻譯的所說 如果cache滿了會清理最近最少使用的緩存對象 mCache = new LruCache<String, Bitmap>(maxMemory / 8) { @Override protected int sizeOf(String key, Bitmap value) { // 計(jì)算一個bitmap的大小 int size = value.getRowBytes() * value.getHeight();// 每一行的字節(jié)數(shù)乘以高度 return size; } }; } public Bitmap getBitmapFromMemory(String url) { return mCache.get(url); } public void setBitmapToMemory(String url, Bitmap bitmap) { mCache.put(url, bitmap); } }
最后一級緩存 本地緩存 把網(wǎng)絡(luò)下載的圖片 文件名以MD5的形式保存到內(nèi)存卡的制定目錄
/** * 本地緩存工具類 * * @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); // 創(chuàng)建文件夾 文件夾不存在或者它不是文件夾 則創(chuàng)建一個文件夾.mkdirs,mkdir的區(qū)別在于假如文件夾有好幾層路徑的話,前者會創(chuàng)建缺失的父目錄 后者不會創(chuàng)建這些父目錄 if (!dirFile.exists() || !dirFile.isDirectory()) { dirFile.mkdirs(); } try { File file = new File(DIR_PATH, MD5Encoder.encode(url)); // 將圖片壓縮保存在本地,參1:壓縮格式;參2:壓縮質(zhì)量(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 { // 網(wǎng)絡(luò)緩存工具類 private NetCacheUtils mNetUtils; // 本地緩存工具類 private LocalCacheUtils mLocalUtils; // 內(nèi)存緩存工具類 private MemoryCacheUtils mMemoryUtils; public MyBitmapUtils() { mMemoryUtils = new MemoryCacheUtils(); mLocalUtils = new LocalCacheUtils(); mNetUtils = new NetCacheUtils(mLocalUtils, mMemoryUtils); } public void display(ImageView imageView, String url) { // 設(shè)置默認(rèn)加載圖片 imageView.setImageResource(R.drawable.news_pic_default); // 先從內(nèi)存緩存加載 Bitmap bitmap = mMemoryUtils.getBitmapFromMemory(url); if (bitmap != null) { imageView.setImageBitmap(bitmap); System.out.println("從內(nèi)存讀取圖片啦..."); return; } // 再從本地緩存加載 bitmap = mLocalUtils.getBitmapFromLocal(url); if (bitmap != null) { imageView.setImageBitmap(bitmap); System.out.println("從本地讀取圖片啦..."); // 給內(nèi)存設(shè)置圖片 mMemoryUtils.setBitmapToMemory(url, bitmap); return; } // 從網(wǎng)絡(luò)緩存加載 mNetUtils.getBitmapFromNet(imageView, url); } }
以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)Android軟件編程有所幫助。
- Android圖片三級緩存開發(fā)
- 淺談Android 中圖片的三級緩存策略
- Android圖片三級緩存的原理及其實(shí)現(xiàn)
- Android中Rxjava實(shí)現(xiàn)三級緩存的兩種方式
- 詳解Android 圖片的三級緩存及圖片壓縮
- Android中圖片的三級緩存機(jī)制
- Android圖片三級緩存策略(網(wǎng)絡(luò)、本地、內(nèi)存緩存)
- Android使用緩存機(jī)制實(shí)現(xiàn)文件下載及異步請求圖片加三級緩存
- android中圖片的三級緩存cache策略(內(nèi)存/文件/網(wǎng)絡(luò))
- Android三級緩存原理講解
相關(guān)文章
Android實(shí)用圖文教程之代碼混淆、第三方平臺加固加密、渠道分發(fā)
這篇文章主要介紹了Android實(shí)用圖文教程之代碼混淆、第三方平臺加固加密、渠道分發(fā),需要的朋友可以參考下2014-12-12Android中創(chuàng)建對話框(確定取消對話框、單選對話框、多選對話框)實(shí)例代碼
這篇文章主要介紹了詳解Android中創(chuàng)建對話框(確定取消對話框、單選對話框、多選對話框)的相關(guān)資料,需要的朋友可以參考下2016-04-04Android事件分發(fā)機(jī)制(上) ViewGroup的事件分發(fā)
這篇文章主要為大家詳細(xì)介紹了Android ViewGroup的事件分發(fā)機(jī)制上篇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01Android RecyclerView實(shí)現(xiàn)下拉刷新和上拉加載
這篇文章主要介紹了Android RecyclerView實(shí)現(xiàn)下拉刷新和上拉加載的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05android USB如何修改VID具體實(shí)現(xiàn)
在android 設(shè)備的Linux 內(nèi)核中把 USB 驅(qū)動的 PID VID 修改以后,也許之前的adb工具就不能識別設(shè)備了,會打印出"device not found"的提示2013-06-06Android實(shí)現(xiàn)簡單計(jì)時器功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)簡單計(jì)時器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-10-10使用Thumbnails實(shí)現(xiàn)圖片指定大小壓縮
這篇文章主要為大家詳細(xì)介紹了使用Thumbnails實(shí)現(xiàn)圖片指定大小壓縮,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08Android啟動頁用戶相關(guān)政策彈框的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android啟動頁用戶相關(guān)政策彈框的實(shí)現(xiàn)方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Android 實(shí)現(xiàn)當(dāng)下最流行的吸頂效果
本文主要介紹了Android 實(shí)現(xiàn)當(dāng)下最流行的吸頂效果的示例代碼。具有很好的參考價值,下面跟著小編一起來看下吧2017-03-03