Android實現(xiàn)圖片異步請求加三級緩存
使用xUtils等框架是很方便,但今天要用代碼實現(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)部實例化了一個靜態(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ù)加載
@Override
protected void onPreExecute() {
super.onPreExecute();
}
// 子線程運行, 異步加載邏輯在此方法中處理
@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);
}
// 主線程運行, 更新進(jìn)度
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
// 主線程運行, 更新主界面
@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就會移動到隊列的頭部。
* 當(dāng)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: 默認(rèn)cache大小是測量的item的數(shù)量,重寫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>
* 他是線程安全的,自動地執(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)的項不在cache中
最重要的大概就是以上幾點: 使用很簡單
來看代碼:
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) {
// 計算一個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軟件編程有所幫助。
相關(guān)文章
Android 再按一次返回鍵退出程序?qū)崿F(xiàn)思路
用戶退出應(yīng)用前給出一個提示是很有必要的,因為可能是用戶并不真的想退出,而只是一不小心按下了返回鍵,大部分應(yīng)用的做法是在應(yīng)用退出去前給出一個Dialog提示框;個人覺得再按一次返回鍵退出程序很有必要,接下來介紹一些簡單實現(xiàn)2013-01-01
Android使用ViewBinding的詳細(xì)步驟(Kotlin簡易版)
最近這段時間在學(xué)習(xí)Kotlin,突然發(fā)現(xiàn)谷歌已經(jīng)把kotlin-android-extensions插件廢棄,目前推薦使用ViewBinding來進(jìn)行替代,接下來通過本文給大家分享Android使用ViewBinding的詳細(xì)步驟,感興趣的朋友一起學(xué)習(xí)吧2021-05-05
Android自定義收音機(jī)搜臺控件RadioRulerView
這篇文章主要為大家詳細(xì)介紹了Android自定義收音機(jī)搜臺控件RadioRulerView的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

