Android框架學習之Volley和Glide詳解
前言
大家在看到這個題目的同時,你們估計會想,Volley與Glide怎么拿來一塊說呢,他們雖然不是一個框架,但有著相同功能,那就是圖片處理方面。首先我們先來看一下什么volley,又什么是glide。
Volley是Google官方出的一套小而巧的異步請求庫,該框架封裝的擴展性很強,支持OkHttp,Volley里面也封裝了ImageLoader,自身作為圖片加載框架,不過這塊功能沒有一些專門的圖片加載框架強大,對于簡單的需求可以使用,對于稍復雜點的需求還是需要用到專門的圖片加載框架。Volley也有缺陷,比如不支持post大數(shù)據(jù),所以不適合上傳文件。不過Volley設計的初衷本身也就是為頻繁的、數(shù)據(jù)量小的網(wǎng)絡請求而生!
個人建議:
如果請求的數(shù)據(jù)比較小的話,建議用volley,因為它代碼量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。
Glide是 Google推薦的圖片加載庫,它可以支持來自ur,文件,支持gif圖片的加載,以及各種圖片顯示前的bitmap處理(例如:圓角圖片,圓形圖片,高斯模糊,旋轉(zhuǎn),灰度等等),緩存處理,請求優(yōu)先級處理,動畫處理,縮略圖處理,圖片大小自定義等等.
他們竟然都是Google的,那為什么出了volley還要出Glide呢,其實他們只是有交集而已,并不是二選一,而是相輔相成。我們想要了解他們,就要先學會怎么用他們,下面寫說一下Volley。下面分為多個小部分來講。
首先 AndroidStudio中引入Volley三種方法
引入volley.jar文件
添加volley到gradle依賴
compile 'com.mcxiaoke.volley:library:1.0.19'
通過git下載volley,添加為項目module
1:StringRequest
先熱熱身,傳入一個百度鏈接,返回一些數(shù)據(jù)。
1.1簡單請求一個網(wǎng)絡地址并返回數(shù)據(jù),創(chuàng)建隊列
RequestQueue queue=Volley.newRequestQueue(context);
1.2在需要的地方創(chuàng)建StringRequest(參數(shù)..)
- GET/POST
- url地址
- 響應監(jiān)聽
- 錯誤監(jiān)聽
String url = "http://www.baidu.com"; StringRequest request = new StringRequest(Request.Method.GET,url,new Response.Listener<String>(){ @Override public void onResponse(String response) {result = SecuritUtil.aesBase64Decode(response); },new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } });
1.3最后處理要加入到隊列中
queue.add(request);
我去,這就可以了,我自己都緊張了,記得以前用httpconnect的時候,寫的真的是多,還要配置很多的東西,就連retrofit都要寫注解什么的。retrofit我之前有些文章,不怎么會用的同志可以去看看。好了,數(shù)據(jù)是出來了,我沒有截圖,大家了解,這什么都不傳是簡單,但如果想傳值呢,那就POST方法唄。
2:POST帶參數(shù)請求
在創(chuàng)建StringRequest方法前,我們先看一下源碼方法,4個參數(shù)。
/** * Creates a new request with the given method. * * @param method the request {@link Method} to use * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; }
2.1:還是一樣的寫創(chuàng)建一個StringRequest,看注釋
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { //成功后 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //失敗后 } }) {//傳值方法書寫位置 @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("name", "liu"); map.put("id", "123456789"); return map; } };//這里需要注意的是getParams()方法是寫在StringRequest(內(nèi))的,括號標紅。
2.2最后要把該對象放在queue中
queue.add(request);
這就完事了,傳值直接寫上就OK了,都是鍵值對的形式。到這估計有人覺得這是傳普通值,如果我傳JSON呢,有有有,下面就是。
3:JSON格式傳參和接受數(shù)據(jù)
這個JSON傳值話也是分GET和PSOT方法,GET一般都不傳值,直接填""。POST則是用專用類JsonObjectRequest,如果你覺得不過癮還可以用
JsonArrayRequest。老規(guī)矩還是先看一下源碼
/** * Creates a new request. * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param requestBody A {@link String} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonObjectRequest(int method, String url, String requestBody, Listener<JSONObject> listener, ErrorListener errorListener) { super(method, url, requestBody, listener, errorListener); }
3.1:請求方式GET,無參數(shù)傳入
JsonObjectRequest json=new JsonObjectRequest(Request.Method.GET, url, "", new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } });
3.2:請求方式POST
JSONObject jsonO=new JSONObject(); try { jsonO.put("name",""); jsonO.put("ID",""); } catch (JSONException e) { e.printStackTrace(); }//創(chuàng)建JSONObject對象 JsonObjectRequest json=new JsonObjectRequest(Request.Method.POST, url, jsonO, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //ok } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //error } });
3.3:最后要把該對象放在queue中
queue.add(request);
到這里volley怎么用來訪問網(wǎng)絡數(shù)據(jù)就完事了,到現(xiàn)在還沒有說他的圖片處理,不過這個框架真心好用,所以就寫的多了點。下面咱們來看一下他的圖片處理
4:ImageRequest, 圖片加載
源碼:圖片URL,響應的回調(diào)接口,最大圖片寬度,最大圖片高度,圖片配置RGB模式,錯誤的回調(diào)接口
最大圖片寬度(高度)如果不寫可以寫0,
/** * Creates a new image request, decoding to a maximum specified width and * height. If both width and height are zero, the image will be decoded to * its natural size. If one of the two is nonzero, that dimension will be * clamped and the other one will be set to preserve the image's aspect * ratio. If both width and height are nonzero, the image will be decoded to * be fit in the rectangle of dimensions width x height while keeping its * aspect ratio. * * @param url URL of the image * @param listener Listener to receive the decoded bitmap * @param maxWidth Maximum width to decode this bitmap to, or zero for none * @param maxHeight Maximum height to decode this bitmap to, or zero for * none * @param scaleType The ImageViews ScaleType used to calculate the needed image size. * @param decodeConfig Format to decode the bitmap to * @param errorListener Error listener, or null to ignore errors */ public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, ScaleType scaleType, Config decodeConfig, Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); setRetryPolicy( new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES, IMAGE_BACKOFF_MULT)); mListener = listener; mDecodeConfig = decodeConfig; mMaxWidth = maxWidth; mMaxHeight = maxHeight; mScaleType = scaleType; }
用法:每個參數(shù)是什么我都在上面寫好,第幾個參數(shù)是干什么的,還有源碼供大家參考。url為圖片地址
ImageRequest request =new ImageRequest(url,Response.Listener<Bitmap>(){ @Override public void onResponse(Bitmap s) { Log.i("aa", "post請求成功" + s); } } ,0,0,Bitmap.config.RGB_565,new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.i("aa", "post請求失敗" + s);});
5:ImageLoader 圖片緩存機制(推薦使用)
在普通版中自身是調(diào)用自己的緩存類,這個是我們不能控制的,如果想要控制的就要自己寫類來實現(xiàn)ImageLoader.ImageCache,這就相當于我們的自定義View,或者自定義適配器,我們可以更好的去控制我們想要的結(jié)果,比如說,我們要它最大緩存量是10M,超過這個值會發(fā)出警報等。
下面來說簡單用法
ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() { @Override public Bitmap getBitmap(String url) { //具體操作,主要針對對緩存數(shù)據(jù)大小、如何緩存。 return null; } @Override public void putBitmap(String url, Bitmap bitmap) { } }); //imgShow是imageview控件。后面參數(shù)分類是失敗和過程時出現(xiàn)的圖片 ImageLoader.ImageListener listener = ImageLoader.getImageListener(imgShow, R.mipmap.ic_launcher, R.drawable.btn_add_true); imageLoader.get(url, listener, 200, 200);
上面這個就可以對圖片進行處理,不過還有一個就是定義接口,里面有兩個方法,一個放一個是取,重點是標紅
public class ImageCache implements ImageLoader.ImageCache{ //LruCache 是專門用于緩存的類,String可以作為緩存入后的名稱,Bitmap是位圖。 public LruCache<String,Bitmap> lruCache; public int maxCache=10 * 1024 *1024;//最大緩存大小 10M public ImageCache (){ lruCache=new LruCache<>(maxCache);//實例化創(chuàng)建 } @Override public Bitmap getBitmap(String url) {//得到位圖 return lruCache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) {//存入位圖 lruCache.put(url,bitmap); } }
6:NetWorkImageView自動適配圖片(控件)
netimg = (NetworkImageView) findViewById(R.id.id_net_img); netimg.setErrorImageResId(R.mipmap.ic_launcher);//錯誤后 netimg.setDefaultImageResId(R.drawable.btn_add_true);//加載中默認 //這里new ImageCache()是上面自己寫的類 netimg.setImageUrl(url,new ImageLoader(queue,new ImageCache()));
到這里volley基本用法就已經(jīng)夠用了,原本想寫點Glide的用法呢,還有對比,這一篇寫的就不少了。大家可以消化一下,下一篇我寫Glide的簡單用法,然后是Volley對比Glide。
總結(jié):
Volley是輕量級的網(wǎng)絡請求框架,如果請求的數(shù)據(jù)比較小的話,建議用volley,因為它代碼量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。
但是如果有一個listview了,GridView了等加載圖片的話,可以用Volley,尤其是最后一個NetWorkImageView,可以自動適配圖片大小,然后統(tǒng)一作出判斷到底該多大才能更好的呈現(xiàn)給用戶。每一個框架都是一些人的心血,肯定是優(yōu)點爆棚的,對于程序員來講一個好的工具對以后的開發(fā)是多么的重要,一個功能省去了一些代碼,功能多了代碼就非誠客觀了,而且簡介明了規(guī)范。謝謝大家的支持。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- Android項目實戰(zhàn)之Glide 高斯模糊效果的實例代碼
- Android 使用Glide加載網(wǎng)絡圖片等比例縮放的實現(xiàn)方法
- Android Glide 4.0+使用詳解
- Android中Glide加載到RelativeLayout背景圖方法示例
- Android中Glide獲取圖片Path、Bitmap用法詳解
- Android將Glide動態(tài)加載不同大小的圖片切圓角與圓形的方法
- Android中Glide庫的使用小技巧總結(jié)
- Android添加glide庫報錯Error: Failed to resolve: com.android.support:support-annotations:26.0.2的解決
- android中Glide實現(xiàn)加載圖片保存至本地并加載回調(diào)監(jiān)聽
- 詳解Android中Glide與CircleImageView加載圓形圖片的問題
- Android利用Glide獲取圖片真正的寬高的實例
- Android如何使用Glide加載清晰長圖
相關(guān)文章
解決eclipse啟動時報錯Failed to create the Java Virtural Machine.問題的
這篇文章主要介紹了解決eclipse啟動時報Failed to create the Java Virtural Machine.問題的方法,感興趣的小伙伴們可以參考一下2016-01-01分享10個很棒的學習Android開發(fā)的網(wǎng)站
我推薦的網(wǎng)站,都是我在學習Android 開發(fā)過程中發(fā)現(xiàn)的好網(wǎng)站,給初學者一些建議,少走一些彎路2015-03-03Android自定義View的三種實現(xiàn)方式總結(jié)
本篇文章主要介紹了Android自定義View的三種實現(xiàn)方式總結(jié),非常具有實用價值,需要的朋友可以參考下。2017-02-02Android 倒計時控件 CountDownView的實例代碼詳解
這篇文章主要介紹了Android 倒計時控件 CountDownView的實例代碼,代碼簡單易懂,非常不錯,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法
android 讀取json數(shù)據(jù),下面小編給大家整理有關(guān)Android中Json數(shù)據(jù)讀取與創(chuàng)建的方法,需要的朋友可以參考下2015-08-08Android EventBus 3.0.0 使用總結(jié)(必看篇)
下面小編就為大家?guī)硪黄狝ndroid EventBus 3.0.0 使用總結(jié)(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05