Android中使用二級緩存、異步加載批量加載圖片完整案例
一、問題描述
Android應(yīng)用中經(jīng)常涉及從網(wǎng)絡(luò)中加載大量圖片,為提升加載速度和效率,減少網(wǎng)絡(luò)流量都會采用二級緩存和異步加載機(jī)制,所謂二級緩存就是通過先從內(nèi)存中獲取、再從文件中獲取,最后才會訪問網(wǎng)絡(luò)。內(nèi)存緩存(一級)本質(zhì)上是Map集合以key-value對的方式存儲圖片的url和Bitmap信息,由于內(nèi)存緩存會造成堆內(nèi)存泄露, 管理相對復(fù)雜一些,可采用第三方組件,對于有經(jīng)驗(yàn)的可自己編寫組件,而文件緩存比較簡單通常自己封裝一下即可。下面就通過案例看如何實(shí)現(xiàn)網(wǎng)絡(luò)圖片加載的優(yōu)化。
二、案例介紹
案例新聞的列表圖片

三、主要核心組件
下面先看看實(shí)現(xiàn)一級緩存(內(nèi)存)、二級緩存(磁盤文件)所編寫的組件
1、MemoryCache
在內(nèi)存中存儲圖片(一級緩存), 采用了1個(gè)map來緩存圖片代碼如下:
public class MemoryCache {
// 最大的緩存數(shù)
private static final int MAX_CACHE_CAPACITY = 30;
//用Map軟引用的Bitmap對象, 保證內(nèi)存空間足夠情況下不會被垃圾回收
private HashMap<String, SoftReference<Bitmap>> mCacheMap =
new LinkedHashMap<String, SoftReference<Bitmap>>() {
private static final long serialVersionUID = 1L;
//當(dāng)緩存數(shù)量超過規(guī)定大?。ǚ祷豻rue)會清除最早放入緩存的
protected boolean removeEldestEntry(
Map.Entry<String,SoftReference<Bitmap>> eldest){
return size() > MAX_CACHE_CAPACITY;};
};
/**
* 從緩存里取出圖片
* @param id
* @return 如果緩存有,并且該圖片沒被釋放,則返回該圖片,否則返回null
*/
public Bitmap get(String id){
if(!mCacheMap.containsKey(id)) return null;
SoftReference<Bitmap> ref = mCacheMap.get(id);
return ref.get();
}
/**
* 將圖片加入緩存
* @param id
* @param bitmap
*/
public void put(String id, Bitmap bitmap){
mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
}
/**
* 清除所有緩存
*/
public void clear() {
try {
for(Map.Entry<String,SoftReference<Bitmap>>entry :mCacheMap.entrySet())
{ SoftReference<Bitmap> sr = entry.getValue();
if(null != sr) {
Bitmap bmp = sr.get();
if(null != bmp) bmp.recycle();
}
}
mCacheMap.clear();
} catch (Exception e) {
e.printStackTrace();}
}
}
2、FileCache
在磁盤中緩存圖片(二級緩存),代碼如下
public class FileCache {
//緩存文件目錄
private File mCacheDir;
/**
* 創(chuàng)建緩存文件目錄,如果有SD卡,則使用SD,如果沒有則使用系統(tǒng)自帶緩存目錄
* @param context
* @param cacheDir 圖片緩存的一級目錄
*/
public FileCache(Context context, File cacheDir, String dir){
if(android.os.Environment.getExternalStorageState().equals、(android.os.Environment.MEDIA_MOUNTED))
mCacheDir = new File(cacheDir, dir);
else
mCacheDir = context.getCacheDir();// 如何獲取系統(tǒng)內(nèi)置的緩存存儲路徑
if(!mCacheDir.exists()) mCacheDir.mkdirs();
}
public File getFile(String url){
File f=null;
try {
//對url進(jìn)行編輯,解決中文路徑問題
String filename = URLEncoder.encode(url,"utf-8");
f = new File(mCacheDir, filename);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return f;
}
public void clear(){//清除緩存文件
File[] files = mCacheDir.listFiles();
for(File f:files)f.delete();
}
}
3、編寫異步加載組件AsyncImageLoader
android中采用單線程模型即應(yīng)用運(yùn)行在UI主線程中,且Android又是實(shí)時(shí)操作系統(tǒng)要求及時(shí)響應(yīng)否則出現(xiàn)ANR錯(cuò)誤,因此對于耗時(shí)操作要求不能阻塞UI主線程,需要開啟一個(gè)線程處理(如本應(yīng)用中的圖片加載)并將線程放入隊(duì)列中,當(dāng)運(yùn)行完成后再通知UI主線程進(jìn)行更改,同時(shí)移除任務(wù)——這就是異步任務(wù),在android中實(shí)現(xiàn)異步可通過本系列一中所用到的AsyncTask或者使用thread+handler機(jī)制,在這里是完全是通過代碼編寫實(shí)現(xiàn)的,這樣我們可以更清晰的看到異步通信的實(shí)現(xiàn)的本質(zhì),代碼如下
public class AsyncImageLoader{
private MemoryCache mMemoryCache;//內(nèi)存緩存
private FileCache mFileCache;//文件緩存
private ExecutorService mExecutorService;//線程池
//記錄已經(jīng)加載圖片的ImageView
private Map<ImageView, String> mImageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
//保存正在加載圖片的url
private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();
/**
* 默認(rèn)采用一個(gè)大小為5的線程池
* @param context
* @param memoryCache 所采用的高速緩存
* @param fileCache 所采用的文件緩存
*/
public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
mMemoryCache = memoryCache;
mFileCache = fileCache;
mExecutorService = Executors.newFixedThreadPool(5);//建立一個(gè)容量為5的固定尺寸的線程池(最大正在運(yùn)行的線程數(shù)量)
}
/**
* 根據(jù)url加載相應(yīng)的圖片
* @param url
* @return 先從一級緩存中取圖片有則直接返回,如果沒有則異步從文件(二級緩存)中取,如果沒有再從網(wǎng)絡(luò)端獲取
*/
public Bitmap loadBitmap(ImageView imageView, String url) {
//先將ImageView記錄到Map中,表示該ui已經(jīng)執(zhí)行過圖片加載了
mImageViews.put(imageView, url);
Bitmap bitmap = mMemoryCache.get(url);//先從一級緩存中獲取圖片
if(bitmap == null) {
enquequeLoadPhoto(url, imageView);//再從二級緩存和網(wǎng)絡(luò)中獲取
}
return bitmap;
}
/**
* 加入圖片下載隊(duì)列
* @param url
*/
private void enquequeLoadPhoto(String url, ImageView imageView) {
//如果任務(wù)已經(jīng)存在,則不重新添加
if(isTaskExisted(url))
return;
LoadPhotoTask task = new LoadPhotoTask(url, imageView);
synchronized (mTaskQueue) {
mTaskQueue.add(task);//將任務(wù)添加到隊(duì)列中
}
mExecutorService.execute(task);//向線程池中提交任務(wù),如果沒有達(dá)到上限(5),則運(yùn)行否則被阻塞
}
/**
* 判斷下載隊(duì)列中是否已經(jīng)存在該任務(wù)
* @param url
* @return
*/
private boolean isTaskExisted(String url) {
if(url == null)
return false;
synchronized (mTaskQueue) {
int size = mTaskQueue.size();
for(int i=0; i<size; i++) {
LoadPhotoTask task = mTaskQueue.get(i);
if(task != null && task.getUrl().equals(url))
return true;
}
}
return false;
}
/**
* 從緩存文件或者網(wǎng)絡(luò)端獲取圖片
* @param url
*/
private Bitmap getBitmapByUrl(String url) {
File f = mFileCache.getFile(url);//獲得緩存圖片路徑
Bitmap b = ImageUtil.decodeFile(f);//獲得文件的Bitmap信息
if (b != null)//不為空表示獲得了緩存的文件
return b;
return ImageUtil.loadBitmapFromWeb(url, f);//同網(wǎng)絡(luò)獲得圖片
}
/**
* 判斷該ImageView是否已經(jīng)加載過圖片了(可用于判斷是否需要進(jìn)行加載圖片)
* @param imageView
* @param url
* @return
*/
private boolean imageViewReused(ImageView imageView, String url) {
String tag = mImageViews.get(imageView);
if (tag == null || !tag.equals(url))
return true;
return false;
}
private void removeTask(LoadPhotoTask task) {
synchronized (mTaskQueue) {
mTaskQueue.remove(task);
}
}
class LoadPhotoTask implements Runnable {
private String url;
private ImageView imageView;
LoadPhotoTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
public void run() {
if (imageViewReused(imageView, url)) {//判斷ImageView是否已經(jīng)被復(fù)用
removeTask(this);//如果已經(jīng)被復(fù)用則刪除任務(wù)
return;
}
Bitmap bmp = getBitmapByUrl(url);//從緩存文件或者網(wǎng)絡(luò)端獲取圖片
mMemoryCache.put(url, bmp);// 將圖片放入到一級緩存中
if (!imageViewReused(imageView, url)) {//若ImageView未加圖片則在ui線程中顯示圖片
BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url); Activity a = (Activity) imageView.getContext();
a.runOnUiThread(bd);//在UI線程調(diào)用bd組件的run方法,實(shí)現(xiàn)為ImageView控件加載圖片
}
removeTask(this);//從隊(duì)列中移除任務(wù)
}
public String getUrl() {
return url;
}
}
/**
*
*由UI線程中執(zhí)行該組件的run方法
*/
class BitmapDisplayer implements Runnable {
private Bitmap bitmap;
private ImageView imageView;
private String url;
public BitmapDisplayer(Bitmap b, ImageView imageView, String url) {
bitmap = b;
this.imageView = imageView;
this.url = url;
}
public void run() {
if (imageViewReused(imageView, url))
return;
if (bitmap != null)
imageView.setImageBitmap(bitmap);
}
}
/**
* 釋放資源
*/
public void destroy() {
mMemoryCache.clear();
mMemoryCache = null;
mImageViews.clear();
mImageViews = null;
mTaskQueue.clear();
mTaskQueue = null;
mExecutorService.shutdown();
mExecutorService = null;
}
}
編寫完成之后,對于異步任務(wù)的執(zhí)行只需調(diào)用AsyncImageLoader中的loadBitmap()方法即可非常方便,對于AsyncImageLoader組件的代碼最好結(jié)合注釋好好理解一下,這樣對于Android中線程之間的異步通信就會有深刻的認(rèn)識。
4、工具類ImageUtil
public class ImageUtil {
/**
* 從網(wǎng)絡(luò)獲取圖片,并緩存在指定的文件中
* @param url 圖片url
* @param file 緩存文件
* @return
*/
public static Bitmap loadBitmapFromWeb(String url, File file) {
HttpURLConnection conn = null;
InputStream is = null;
OutputStream os = null;
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
is = conn.getInputStream();
os = new FileOutputStream(file);
copyStream(is, os);//將圖片緩存到磁盤中
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
try {
if(os != null) os.close();
if(is != null) is.close();
if(conn != null) conn.disconnect();
} catch (IOException e) { }
}
}
public static Bitmap decodeFile(File f) {
try {
return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
} catch (Exception e) { }
return null;
}
private static void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
四、測試應(yīng)用
組件之間的時(shí)序圖:

1、編寫MainActivity
public class MainActivity extends Activity {
ListView list;
ListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
adapter=new ListViewAdapter(this, mStrings);
list.setAdapter(adapter);
}
public void onDestroy(){
list.setAdapter(null);
super.onDestroy();
adapter.destroy();
}
private String[] mStrings={
"http://news.jb51.net/UserFiles/x_Image/x_20150606083511_0.jpg",
"http://news.jb51.net/UserFiles/x_Image/x_20150606082847_0.jpg",
…..};
2、編寫適配器
public class ListViewAdapter extends BaseAdapter {
private Activity mActivity;
private String[] data;
private static LayoutInflater inflater=null;
private AsyncImageLoader imageLoader;//異步組件
public ListViewAdapter(Activity mActivity, String[] d) {
this.mActivity=mActivity;
data=d;
inflater = (LayoutInflater)mActivity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
MemoryCache mcache=new MemoryCache();//內(nèi)存緩存
File sdCard = android.os.Environment.getExternalStorageDirectory();//獲得SD卡
File cacheDir = new File(sdCard, "jereh_cache" );//緩存根目錄
FileCache fcache=new FileCache(mActivity, cacheDir, "news_img");//文件緩存
imageLoader = new AsyncImageLoader(mActivity, mcache,fcache);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh=null;
if(convertView==null){
convertView = inflater.inflate(R.layout.item, null);
vh=new ViewHolder();
vh.tvTitle=(TextView)convertView.findViewById(R.id.text);
vh.ivImg=(ImageView)convertView.findViewById(R.id.image);
convertView.setTag(vh);
}else{
vh=(ViewHolder)convertView.getTag();
}
vh.tvTitle.setText("標(biāo)題信息測試———— "+position);
vh.ivImg.setTag(data[position]);
//異步加載圖片,先從一級緩存、再二級緩存、最后網(wǎng)絡(luò)獲取圖片
Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]);
if(bmp == null) {
vh.ivImg.setImageResource(R.drawable.default_big);
} else {
vh.ivImg.setImageBitmap(bmp);
}
return convertView;
}
private class ViewHolder{
TextView tvTitle;
ImageView ivImg;
}
public void destroy() {
imageLoader.destroy();
}
}
想要了解更多內(nèi)容的小伙伴,可以點(diǎn)擊查看源碼,親自運(yùn)行測試。
- android CursorLoader用法介紹
- android異步加載圖片并緩存到本地實(shí)現(xiàn)方法
- Android中ListView異步加載圖片錯(cuò)位、重復(fù)、閃爍問題分析及解決方案
- Android 異步加載圖片分析總結(jié)
- Android加載對話框同時(shí)異步執(zhí)行實(shí)現(xiàn)方法
- Android實(shí)現(xiàn)Listview異步加載網(wǎng)絡(luò)圖片并動(dòng)態(tài)更新的方法
- Android 異步加載圖片的實(shí)例代碼
- Android App中實(shí)現(xiàn)圖片異步加載的實(shí)例分享
- Android程序開發(fā)ListView+Json+異步網(wǎng)絡(luò)圖片加載+滾動(dòng)翻頁的例子(圖片能緩存,圖片不錯(cuò)亂)
- 使用CursorLoader異步加載數(shù)據(jù)
相關(guān)文章
RxJava加Retrofit文件分段上傳實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了RxJava加Retrofit文件分段上傳實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Android Http協(xié)議訪問網(wǎng)絡(luò)實(shí)例(3種)
本篇文章主要介紹了Android Http協(xié)議訪問網(wǎng)絡(luò)實(shí)例(3種),具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07
Android APK使用Debug簽名重新打包 Eclipse更改默認(rèn)Debug簽名
這篇文章主要介紹了Android APK使用Debug簽名重新打包 Eclipse更改默認(rèn)Debug簽名等內(nèi)容,需要的朋友可以參考下2015-04-04
21天學(xué)習(xí)android開發(fā)教程之MediaPlayer
21天學(xué)習(xí)android開發(fā)教程之MediaPlayer,MediaPlayer可以播放音頻和視頻,操作相對簡單,感興趣的小伙伴們可以參考一下2016-02-02
Android數(shù)據(jù)庫中事務(wù)操作方法之銀行轉(zhuǎn)賬示例
這篇文章主要介紹了Android數(shù)據(jù)庫中事務(wù)操作方法之銀行轉(zhuǎn)賬,以具體的銀行轉(zhuǎn)賬為例分析了Android數(shù)據(jù)庫操作中事務(wù)的使用與回滾相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
android調(diào)用WebService實(shí)例分析
這篇文章主要介紹了android調(diào)用WebService的方法,以實(shí)例形式較為詳細(xì)的分析了WebService的調(diào)用原理與具體使用方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10
Android?Bugreport實(shí)現(xiàn)原理深入分析
這篇文章主要介紹了Android?Bugreport實(shí)現(xiàn)原理,Bugreport主要用于分析手機(jī)的狀態(tài),在應(yīng)用開發(fā)中,程序的調(diào)試分析是日常生產(chǎn)中進(jìn)程會進(jìn)行的工作,Bugreport就是很常用的工具,需要的朋友可以參考下2024-05-05

