Android異步載入學習筆記之四:利用緩存優化網絡載入圖片及ListView載入優化
假設不做不論什麽處理。直接用網絡載入圖片在網速快的情況下可能沒什麽不好的感覺。可是假設使用移動流量或是網絡不好的時候。問題就來了,要麽用戶會抱怨流量使用太多。要麽抱怨圖片載入太慢。如論從哪個角度出發,都不是好的體驗!
要提高用戶體驗,我們就要使用緩存。Android中數據緩存的方式有非常多,相關介紹的文章也比較多。比方http://blog.csdn.net/dahuaishu2010_/article/details/17093139和http://www.jb51.net/article/38162.htm等。今天學習是是Lru緩存。
Lru(Least Recently Used)近期最少使用算法,即是在一定條件下LRU緩存是把近期最少使用的數據移除。讓給最新讀取的數據。而往往最常讀取的,也是讀取次數最多的。所以。利用LRU緩存,我們可以提高應用的效率及用戶體驗度。Andorid本身提供了LruCache類來實現這個緩存算法 。
在ImageLoader中利用LruCache緩存:
public class ImageLoader {
private LruCache<String, Bitmap> mCaches;// 創建LruCache對象
private ImageView mImageView;
private ListView listView;
private Set<ImageAsyncTask> mTask;
@SuppressLint("NewApi")
public ImageLoader(ListView listView) {
mTask = new HashSet<ImageAsyncTask>();
int maxMemory = (int) Runtime.getRuntime().maxMemory();// 獲取最大可用內存
int cacheSize = maxMemory / 8;// 設置緩存數據的最大占用內存量為最大值1/8
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
}
};
}
@SuppressLint("NewApi")
/**
* 添加緩存數據。添加前推斷數據是否存在
* @description:
* @author ldm
* @date 2015-8-11 下午7:51:04
*/
public void setLruCaches(String url, Bitmap bitmap) {
if (getLruCaches(url) == null) {// 假設緩存中不存在url相應的Bitmap。則把bitmap增加mCaches
mCaches.put(url, bitmap);
}
}
/**
* 從緩存中獲取數據
* @description:
* @author ldm
* @date 2015-8-11 下午7:51:22
*/
@SuppressLint("NewApi")
public Bitmap getLruCaches(String url) {
return mCaches.get(url);// 通過url獲取緩存中相應的bitmap
}
/**
*從url中獲取到Bitmap
* @description:
* @author ldm
* @date 2015-8-11 下午1:55:12
*/
public Bitmap getBitmapByUrl(String urlStr) {
Bitmap bitmap = null;
InputStream is = null;
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
con.disconnect();
return bitmap;
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void loadImgByAsyncTask(ImageView img, String url) {
mImageView = img;
// 從緩存中取出圖片
Bitmap bitmap = getLruCaches(url);
if (bitmap == null) {// 假設能在中無圖片,則就從網絡下載
mImageView.setImageResource(R.drawable.ic_launcher);//設置默認圖片
new ImageAsyncTask(url).execute(url);
}
else {// 緩存中有圖片。則直接顯示出來
mImageView.setImageBitmap(bitmap);
}
}
private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView imageView;
private String mUrl;
public ImageAsyncTask(String mUrl) {
this.mUrl = mUrl;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = getBitmapByUrl(params[0]);// 獲取圖片
if (bitmap != null) {
setLruCaches(params[0], bitmap);
}
return getBitmapByUrl(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
ImageView img = (ImageView) listView.findViewWithTag(mUrl);
if (img != null && result != null) {
imageView.setImageBitmap(result);
}
mTask.remove(this);
}
}
public void setImageView(int start, int end) {
for (int i = start; i < end; i++) {
String url = DataAdapter.URLS[i];
Bitmap bitmap = getLruCaches(url);
if (bitmap == null) {// 假設能在中無圖片,則就從網絡下載
ImageAsyncTask task = new ImageAsyncTask(url);
task.execute(url);
mTask.add(task);
}
else {// 緩存中有圖片,則直接顯示出來
ImageView img = (ImageView) listView.findViewWithTag(url);
img.setImageBitmap(bitmap);
}
}
}
public void stopAllTask(){
if(mTask.size()>0){
for (ImageAsyncTask task : mTask) {
task.cancel(false);
}
}
}
}
相應ListView的數據適配器DataAdapter:
public class DataAdapter extends BaseAdapter implements OnScrollListener {
private Context mContext;
private List<DataBean> list;
private ImageLoader mImageLoader;
private int mSart;
private int mEnd;
public static String[] URLS;
private ListView listView;
private boolean isFirst;//是否是第一次進入
public DataAdapter(Context mContext, List<DataBean> list, ListView listView) {
this.listView = listView;
this.mContext = mContext;
this.list = list;
mImageLoader = new ImageLoader(listView);
URLS = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
URLS[i] = list.get(i).getImgUrl();
}
isFirst=true;
listView.setOnScrollListener(this);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int arg0, View view, ViewGroup arg2) {
ViewHolder holder = null;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, null);
holder.iv = (ImageView) view.findViewById(R.id.item_iv);
holder.titleTv = (TextView) view.findViewById(R.id.item_title);
holder.contentTv = (TextView) view.findViewById(R.id.item_content);
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
}
holder.titleTv.setText(list.get(arg0).getTitle());
holder.contentTv.setText(list.get(arg0).getContent());
holder.iv.setTag(list.get(arg0).getImgUrl());// 為ImageView設置tag
// new ImageLoader().loaderImageThread(holder.iv, list.get(arg0).getImgUrl());//用線程載入圖片
mImageLoader.loadImgByAsyncTask(holder.iv, list.get(arg0).getImgUrl());
return view;
}
/***
* ListView在流動過程中調用
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mSart = firstVisibleItem;// 可見第一個item
mEnd = firstVisibleItem + visibleItemCount;// 可見的最後一個item
if(isFirst&&visibleItemCount>0){//第一次載入數據時數據處理
mImageLoader.setImageView(mSart, mEnd);
isFirst=false;
}
}
/***
* ListView在流動狀態變化時調用
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {// 流動停止,此時載入可見項數據
mImageLoader.setImageView(mSart, mEnd);
}
else {// 停止載入數據
mImageLoader.stopAllTask();
}
}
class ViewHolder {
TextView titleTv;
TextView contentTv;
ImageView iv;
}
}
Android異步載入學習筆記之四:利用緩存優化網絡載入圖片及ListView載入優化