欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android框架學(xué)習(xí)之Volley和Glide詳解

 更新時(shí)間:2018年05月06日 12:15:00   作者:CMusketeer  
這篇文章主要給大家介紹了關(guān)于Android框架學(xué)習(xí)之Volley和Glide的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)各位Android開(kāi)發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

大家在看到這個(gè)題目的同時(shí),你們估計(jì)會(huì)想,Volley與Glide怎么拿來(lái)一塊說(shuō)呢,他們雖然不是一個(gè)框架,但有著相同功能,那就是圖片處理方面。首先我們先來(lái)看一下什么volley,又什么是glide。

Volley是Google官方出的一套小而巧的異步請(qǐng)求庫(kù),該框架封裝的擴(kuò)展性很強(qiáng),支持OkHttp,Volley里面也封裝了ImageLoader,自身作為圖片加載框架,不過(guò)這塊功能沒(méi)有一些專門(mén)的圖片加載框架強(qiáng)大,對(duì)于簡(jiǎn)單的需求可以使用,對(duì)于稍復(fù)雜點(diǎn)的需求還是需要用到專門(mén)的圖片加載框架。Volley也有缺陷,比如不支持post大數(shù)據(jù),所以不適合上傳文件。不過(guò)Volley設(shè)計(jì)的初衷本身也就是為頻繁的、數(shù)據(jù)量小的網(wǎng)絡(luò)請(qǐng)求而生!

個(gè)人建議:

如果請(qǐng)求的數(shù)據(jù)比較小的話,建議用volley,因?yàn)樗a量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。

Glide是 Google推薦的圖片加載庫(kù),它可以支持來(lái)自u(píng)r,文件,支持gif圖片的加載,以及各種圖片顯示前的bitmap處理(例如:圓角圖片,圓形圖片,高斯模糊,旋轉(zhuǎn),灰度等等),緩存處理,請(qǐng)求優(yōu)先級(jí)處理,動(dòng)畫(huà)處理,縮略圖處理,圖片大小自定義等等.

他們竟然都是Google的,那為什么出了volley還要出Glide呢,其實(shí)他們只是有交集而已,并不是二選一,而是相輔相成。我們想要了解他們,就要先學(xué)會(huì)怎么用他們,下面寫(xiě)說(shuō)一下Volley。下面分為多個(gè)小部分來(lái)講。

首先 AndroidStudio中引入Volley三種方法

引入volley.jar文件

添加volley到gradle依賴

compile 'com.mcxiaoke.volley:library:1.0.19'

通過(guò)git下載volley,添加為項(xiàng)目module

1:StringRequest

先熱熱身,傳入一個(gè)百度鏈接,返回一些數(shù)據(jù)。

1.1簡(jiǎn)單請(qǐng)求一個(gè)網(wǎng)絡(luò)地址并返回?cái)?shù)據(jù),創(chuàng)建隊(duì)列

RequestQueue queue=Volley.newRequestQueue(context);

1.2在需要的地方創(chuàng)建StringRequest(參數(shù)..)

  • GET/POST
  • url地址
  • 響應(yīng)監(jiān)聽(tīng)
  • 錯(cuò)誤監(jiān)聽(tīng)
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最后處理要加入到隊(duì)列中

queue.add(request);

我去,這就可以了,我自己都緊張了,記得以前用httpconnect的時(shí)候,寫(xiě)的真的是多,還要配置很多的東西,就連retrofit都要寫(xiě)注解什么的。retrofit我之前有些文章,不怎么會(huì)用的同志可以去看看。好了,數(shù)據(jù)是出來(lái)了,我沒(méi)有截圖,大家了解,這什么都不傳是簡(jiǎn)單,但如果想傳值呢,那就POST方法唄。

2:POST帶參數(shù)請(qǐng)求

在創(chuàng)建StringRequest方法前,我們先看一下源碼方法,4個(gè)參數(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:還是一樣的寫(xiě)創(chuàng)建一個(gè)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) {
        //失敗后
   }
  }) {//傳值方法書(shū)寫(xiě)位置
   @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()方法是寫(xiě)在StringRequest(內(nèi))的,括號(hào)標(biāo)紅。

2.2最后要把該對(duì)象放在queue中

queue.add(request);

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

3:JSON格式傳參和接受數(shù)據(jù)

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

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:請(qǐng)求方式GET,無(wú)參數(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:請(qǐng)求方式POST

JSONObject jsonO=new JSONObject();
  try {
   jsonO.put("name","");
   jsonO.put("ID","");
   
  } catch (JSONException e) {
   e.printStackTrace();
  }//創(chuàng)建JSONObject對(duì)象
  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:最后要把該對(duì)象放在queue中

queue.add(request);

到這里volley怎么用來(lái)訪問(wèn)網(wǎng)絡(luò)數(shù)據(jù)就完事了,到現(xiàn)在還沒(méi)有說(shuō)他的圖片處理,不過(guò)這個(gè)框架真心好用,所以就寫(xiě)的多了點(diǎn)。下面咱們來(lái)看一下他的圖片處理

4:ImageRequest, 圖片加載

 

源碼:圖片URL,響應(yīng)的回調(diào)接口,最大圖片寬度,最大圖片高度,圖片配置RGB模式,錯(cuò)誤的回調(diào)接口
最大圖片寬度(高度)如果不寫(xiě)可以寫(xiě)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;
 }

用法:每個(gè)參數(shù)是什么我都在上面寫(xiě)好,第幾個(gè)參數(shù)是干什么的,還有源碼供大家參考。url為圖片地址

ImageRequest request =new ImageRequest(url,Response.Listener<Bitmap>(){
 @Override
    public void onResponse(Bitmap s) {
 
     Log.i("aa", "post請(qǐng)求成功" + s);
     
    }
   } ,0,0,Bitmap.config.RGB_565,new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
          Log.i("aa", "post請(qǐng)求失敗" + s);});

5:ImageLoader 圖片緩存機(jī)制(推薦使用)

在普通版中自身是調(diào)用自己的緩存類,這個(gè)是我們不能控制的,如果想要控制的就要自己寫(xiě)類來(lái)實(shí)現(xiàn)ImageLoader.ImageCache,這就相當(dāng)于我們的自定義View,或者自定義適配器,我們可以更好的去控制我們想要的結(jié)果,比如說(shuō),我們要它最大緩存量是10M,超過(guò)這個(gè)值會(huì)發(fā)出警報(bào)等。

下面來(lái)說(shuō)簡(jiǎn)單用法

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

    return null;
   }

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

   }
  });
//imgShow是imageview控件。后面參數(shù)分類是失敗和過(guò)程時(shí)出現(xiàn)的圖片
  ImageLoader.ImageListener listener = ImageLoader.getImageListener(imgShow, R.mipmap.ic_launcher, R.drawable.btn_add_true);
  imageLoader.get(url, listener, 200, 200);

上面這個(gè)就可以對(duì)圖片進(jìn)行處理,不過(guò)還有一個(gè)就是定義接口,里面有兩個(gè)方法,一個(gè)放一個(gè)是取,重點(diǎn)是標(biāo)紅

public class ImageCache implements ImageLoader.ImageCache{
//LruCache 是專門(mén)用于緩存的類,String可以作為緩存入后的名稱,Bitmap是位圖。
 public LruCache<String,Bitmap> lruCache;
 public int maxCache=10 * 1024 *1024;//最大緩存大小 10M
 public ImageCache (){
  lruCache=new LruCache<>(maxCache);//實(shí)例化創(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自動(dòng)適配圖片(控件)


netimg = (NetworkImageView) findViewById(R.id.id_net_img);
netimg.setErrorImageResId(R.mipmap.ic_launcher);//錯(cuò)誤后
netimg.setDefaultImageResId(R.drawable.btn_add_true);//加載中默認(rèn)
//這里new ImageCache()是上面自己寫(xiě)的類
netimg.setImageUrl(url,new ImageLoader(queue,new ImageCache()));

到這里volley基本用法就已經(jīng)夠用了,原本想寫(xiě)點(diǎn)Glide的用法呢,還有對(duì)比,這一篇寫(xiě)的就不少了。大家可以消化一下,下一篇我寫(xiě)Glide的簡(jiǎn)單用法,然后是Volley對(duì)比Glide。

總結(jié):

Volley是輕量級(jí)的網(wǎng)絡(luò)請(qǐng)求框架,如果請(qǐng)求的數(shù)據(jù)比較小的話,建議用volley,因?yàn)樗a量小,效果高,但是如果是下載大型文件(視頻),那就不要用它了。

但是如果有一個(gè)listview了,GridView了等加載圖片的話,可以用Volley,尤其是最后一個(gè)NetWorkImageView,可以自動(dòng)適配圖片大小,然后統(tǒng)一作出判斷到底該多大才能更好的呈現(xiàn)給用戶。每一個(gè)框架都是一些人的心血,肯定是優(yōu)點(diǎn)爆棚的,對(duì)于程序員來(lái)講一個(gè)好的工具對(duì)以后的開(kāi)發(fā)是多么的重要,一個(gè)功能省去了一些代碼,功能多了代碼就非誠(chéng)客觀了,而且簡(jiǎn)介明了規(guī)范。謝謝大家的支持。

好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論