1. 程式人生 > >Android框架之Volley與Glide

Android框架之Volley與Glide

cat name 圖片緩存 上傳文件 bsp 怎麽 每一個 ons exc

PS:在看到這個題目的同時,你們估計會想,Volley與Glide怎麽拿來一塊說呢,他們雖然不是一個框架,但有著相同功能,那就是圖片處理方面。首先我們先來看一下什麽volley,又什麽是glide。

Volley是Google官方出的一套小而巧的異步請求庫,該框架封裝的擴展性很強,支持OkHttp,Volley裏面也封裝了ImageLoader,自身作為圖片加載框架,不過這塊功能沒有一些專門的圖片加載框架強大,對於簡單的需求可以使用,對於稍復雜點的需求還是需要用到專門的圖片加載框架。Volley也有缺陷,比如不支持post大數據,所以不適合上傳文件。不過Volley設計的初衷本身也就是為頻繁的、數據量小的網絡請求而生!

個人建議:

如果請求的數據比較小的話,建議用volley,因為它代碼量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。

Glide是 Google推薦的圖片加載庫,它可以支持來自ur,文件,支持gif圖片的加載,以及各種圖片顯示前的bitmap處理(例如:圓角圖片,圓形圖片,高斯模糊,旋轉,灰度等等),緩存處理,請求優先級處理,動畫處理,縮略圖處理,圖片大小自定義等等. 他們竟然都是Google的,那為什麽出了volley還要出Glide呢,其實他們只是有交集而已,並不是二選一,而是相輔相成。我們想要了解他們,就要先學會怎麽用他們,下面寫說一下Volley。下面分為多個小部分來講。

首先 AndroidStudio中引入Volley三種方法

  • 引入volley.jar文件
  • 添加volley到gradle依賴
    compile ‘com.mcxiaoke.volley:library:1.0.19‘
  • 通過git下載volley,添加為項目module

1:StringRequest

先熱熱身,傳入一個百度鏈接,返回一些數據。

1.1簡單請求一個網絡地址並返回數據,創建隊列

RequestQueue queue=Volley.newRequestQueue(context);

1.2在需要的地方創建StringRequest(參數..)

  • GET/POST
  • url地址
  • 響應監聽
  • 錯誤監聽
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我之前有些文章,不怎麽會用的同誌可以去看看。好了,數據是出來了,我沒有截圖,大家了解,這什麽都不傳是簡單,但如果想傳值呢,那就POST方法唄。

2:POST帶參數請求

在創建StringRequest方法前,我們先看一下源碼方法,4個參數。

 /**
     * 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:還是一樣的寫創建一個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(內)的,括號標紅。

2.2最後要把該對象放在queue中

queue.add(request);

這就完事了,傳值直接寫上就OK了,都是鍵值對的形式。到這估計有人覺得這是傳普通值,如果我傳JSON呢,有有有,下面就是。

3:JSON格式傳參和接受數據

這個JSON傳值話也是分GET和PSOT方法,GET一般都不傳值,直接填""。POST則是用專用類JsonObjectRequest,如果你覺得不過癮還可以用

JsonArrayRequest。老規矩還是先看一下源碼
/**
     * 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,無參數傳入

 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();
        }//創建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怎麽用來訪問網絡數據就完事了,到現在還沒有說他的圖片處理,不過這個框架真心好用,所以就寫的多了點。下面咱們來看一下他的圖片處理

4:ImageRequest, 圖片加載

技術分享圖片 源碼:圖片URL,響應的回調接口,最大圖片寬度,最大圖片高度,圖片配置RGB模式,錯誤的回調接口 最大圖片寬度(高度)如果不寫可以寫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;
    }

用法:每個參數是什麽我都在上面寫好,第幾個參數是幹什麽的,還有源碼供大家參考。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 圖片緩存機制(推薦使用)

在普通版中自身是調用自己的緩存類,這個是我們不能控制的,如果想要控制的就要自己寫類來實現ImageLoader.ImageCache,這就相當於我們的自定義View,或者自定義適配器,我們可以更好的去控制我們想要的結果,比如說,我們要它最大緩存量是10M,超過這個值會發出警報等。

下面來說簡單用法

ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String url) {
           //具體操作,主要針對對緩存數據大小、如何緩存。

                return null;
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {

            }
        });
//imgShow是imageview控件。後面參數分類是失敗和過程時出現的圖片
        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);//實例化創建
    }
    @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基本用法就已經夠用了,原本想寫點Glide的用法呢,還有對比,這一篇寫的就不少了。大家可以消化一下,下一篇我寫Glide的簡單用法,然後是Volley對比Glide。

總結:

Volley是輕量級的網絡請求框架,如果請求的數據比較小的話,建議用volley,因為它代碼量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。

但是如果有一個listview了,GridView了等加載圖片的話,可以用Volley,尤其是最後一個NetWorkImageView,可以自動適配圖片大小,然後統一作出判斷到底該多大才能更好的呈現給用戶。每一個框架都是一些人的心血,肯定是優點爆棚的,對於程序員來講一個好的工具對以後的開發是多麽的重要,一個功能省去了一些代碼,功能多了代碼就非誠客觀了,而且簡介明了規範。謝謝大家的支持。

Android框架之Volley與Glide