Android Volley架構的使用
Volley架構的學習馬上就可以“殺青”了,哈哈,有木有點小激動呢,之所以將這個架構分成三篇來寫,而且涉及的細節比較多,是因為考慮到後面還要學習幾個Android http架構,只要認認真真看完volley架構的學習,後面幾個架構的學習簡直“易如反掌”。
這篇主要介紹圖片請求以及緩衝的問題,這在開發中似乎是最常用到的,所以最後咱們一起來做個Demo來練習一下!
文章結構如下:
Image Request
為了更方便的使用Volley中的圖片請求,我們同樣先在ApplicationController類中封裝一個ImageLoader
public class ApplicationController extends Application{ /*前面寫過的方法不再贅述*/ private ImageLoader imageLoader; .... public ImageLoader getImageLoader(){ getRequestQueue(); //如果imageLoader為空白則建立它,第二個參數代表處理映像緩衝的類 if(imageLoader==null){ imageLoader=new ImagerLoader(this.reqQueue,new LruBitmapCache()); } return this.imageLoader; } } public class LruBitmapCache extends LruCache implements ImageCache{ public static int getDefaultLruCacheSize(){ final int maxMemory=(int)(Runtime.getRuntime().maxMemory/1024); final int cacheSize=maxMemory/8; return cacheSize; } public LruBitmapCache(){ this(getDefaultLruBitmapCacheSize); } public LruBitmapCache(int sizeInKiloBytes){ super(sizeInkiloBytes); } @Override public int sizeOf(String key,Bitmap Value){ return value.getRowBytes()*value.getHeight()/1024; } @Override public Bitmap getBitmap(String url){ return get(url); } @Override public void putBitmap(String url,Bitmap bitmap){ put(url,bitmap); } }
完成上述步驟後,在使用的時候我們首先需要擷取ImageLoader對象
ImageLoader imageLoader=ApplicationController.getInstance().getImageLoader();
將圖片載入ImageView
可以使用Volley自己提供的一個Image視圖,NetworkImageView,幾行代碼就可以搞定
//將NetworkImageView布局在布局檔案中NetworkImageView imageView=(NetworkImageView)findViewById(R.id.networkimageview); //需要用到imageLoader imageView.setImageUrl(url,imageLoader);
如果要將圖片直接載入ImageView,可以通過以下方法:
ImageLoader imageLoader=ApplicationController.getInstance().getImageLoader();imageLoader.get(url,new ImageListener(){ @Override public void onResponse(ImageContainer response,boolean arg) { if(response.getBitmap()!=null){ //設定imageView imageView.setImageBitmap(response.getBitmap()); } } @Override public void onErrorResponse(VolleyError error){ Log.e(TAG,Image Error+error.getMessage()); } });
Volley Cache
Volley有著強大的緩衝機制用來維護請求到的緩衝,這節省了不必要的網路消耗和等待時間,下面是一些關於緩衝的常用方法
從緩衝中讀取請求:即先從緩衝讀取看是否有快取資料,如果沒有則請求網路資料
Cache cache=ApplicationController.getRequestQueue().getCache(); Entry entry=cache.get(url); if(entry!=null){ try{ String data=new String(entry.data,Utf-8); //處理data,將其轉化為JSON,XML,Bitmap等等 }catch(UnspportedEncodingException e){ e.printStackTrace(); } }else{ //緩衝中不存在,做網路請求 }
緩衝失效:緩衝失效並不意味這刪除緩衝,volley仍將使用緩衝對象,直到伺服器返回新資料,一旦接收到新資料,將覆蓋原來的緩衝
ApplicationController.getInstance().getRequestQueue().getCache().invalidate(url,true);
關閉緩衝:如果你想禁用特定Url的緩衝可以使用以下方法
StringRequest req=new StringRequest(...);req.setShouldCache(false);
刪除來自特定url的緩衝
ApplicationController.getInstance().getRequestQueue().getCache().remove(url);
刪除所有緩衝
ApplicationController.getInstance().getRequestQueue().getCache().clear(url);
通過Volley擷取資料填充自訂ListView限於篇幅的問題放到下篇文章中來寫->_<總結:
綜上,已經學完了Volley架構的使用,在實際應用中遇到具體的問題需要具體考慮,必要時要學會查閱資料,除了以上幾篇提到的參考資料,最好能翻牆去看看google官方關於Volley的文檔,我想基本上能解決我們所碰到的問題。