Android第三方網絡資源加載框架Volley

Volley的簡介和特點

Volley 是2013年發佈的Android平臺網絡通信庫: 使用場景 併發,效率 性能
地址 :https://android.googlesource.com/platform/frameworks/volley/
Github地址:https://github.com/mcxiaoke/android-volley

優點
1.通信更快,更簡單
2.網絡請求的排序,優先級處理
3.網絡請求的緩存
4.多級別的取消請求
5.擴展性強

缺點
不適合數據的上傳和下載

爲什麼使用Volley
1.高效的Get/Post方式的數據請求交互
2.網絡圖片加載和緩存
3.谷歌官方推出
4.性能穩定強勁

Volley工作示意圖

這裏寫圖片描述

用法

1.導包(寫在buil.gradle文件的dependencies代碼塊)

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

2.創建請求隊列

RequestQueue requestQueue = Volley.newRequestQueue(this);

3.創建具體請求
如:
請求String(Json等)

StringRequest request = new StringRequest(url, com.android.volley.Response.Listener<java.lang.String> listener, com.android.volley.Response.ErrorListener errorListener);
 requestQueue.add(request);

請求圖片

ImageLoader imageLoader = new ImageLoader(requestQueue, ImageLoader.ImageCache imageCache);
imageLoader.get(URL, ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher));

4.取消請求

requestQueue.cancelAll(TAG);

一些相關操作
取消請求getRequstQuene().cancelAll()
關閉Cacherequest.setShouldCache()
刪除某一URL的Cache刪除getRequstQuene().getCache().remove(url)
刪除所有的CachegetRequstQuene().getCache().clear()

示例:

1.導包

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

2.佈局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="78dp"
        android:text="New Text"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/textView2"
        android:layout_toRightOf="@+id/textView2"
        android:src="@mipmap/ic_launcher"/>

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>

3.java代碼

1)資源URL和相關定義

public static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=13812345678&key=daf8fa858c330b22e342c882bcbac622";
public static final String URL_POST = "http://apis.juhe.cn/mobile/get ";
public static final String URL_IMG= "http://img2.3lian.com/2014/f7/5/d/22.jpg";
public static String TAG = "QL";
private RequestQueue requestQueue;
private TextView textView;
private TextView textView1;
private ImageView imageView;

2)實例化請求隊列
普通的方法

requestQueue = Volley.newRequestQueue(this);

使用工廠的方法,詳情請移步最後“請求網絡圖片”—–> 2.1.2

requestQueue2 = VolleyFactroy.getInstance(this).getRequestQueue();

3)————————–>>>>>

使用Get方式請求Json數據

public void get() {
        StringRequest request = new StringRequest(URL_GET, new Response.Listener<String>() {
            @Override//成功的返回
            public void onResponse(String response) {
                textView.setText(response.toString());//將數據取出
            }
        }, new Response.ErrorListener(){

            @Override//失敗的返回
            public void onErrorResponse(VolleyError error) {
                textView1.setText(error.toString());
            }
        });
        request.setTag(TAG);//設置TAG,方便取消請求
        requestQueue.add(request);//加入請求隊列
    }

使用Post方式請求Json數據

public  void post(){
        StringRequest request = new StringRequest(Request.Method.POST, URL_POST, new Response.Listener<String>() {//設置請求方式爲post
            @Override
            public void onResponse(String response) {
                textView.setText(response.toString());//將數據取出
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView1.setText(error.toString());
            }
        }){
            @Override//重寫getParams()方法,用於包裝數據
            protected Map<String, String> getParams() throws AuthFailureError {
                //用map將鍵值對進行封裝
                HashMap<String, String> map = new HashMap<>();
                map.put("phone", "18977921449");
                map.put("key", "daf8fa858c330b22e342c882bcbac622");
                return map;
            }
        };
        request.setTag(TAG);
        requestQueue.add(request);
}

請求網絡圖片

1.使用自帶networkImageView控件顯示圖片

private void getNetWorkImage() {
        NetworkImageView networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);//取出networkImageView

        networkImageView.setDefaultImageResId(R.mipmap.ic_launcher);//設置默認圖片
        networkImageView.setErrorImageResId(R.mipmap.ic_launcher);//設置加載失敗圖片
        networkImageView.setTag(TAG);//設置tag,方便取消請求
        networkImageView.setImageUrl(URL_IMG, new ImageLoader(requestQueue, new ImageLoader.ImageCache() {

            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }

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

            }
        }));
}

2.使用系統ImageView控件顯示圖片

2.1創建ImageLoader請求

2.1.1一般的imageLoader

ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }

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

2.1.2使用工廠的imageLoader,使用自定義實例工廠和圖片緩存類
用工廠獲取對象。得到RequestQueue,避免重複new。得到圖片緩存
請向下移步————>>>

2.2綁定給imageView
方式1

imageLoader.get(URL_IMG, new ImageLoader.ImageListener() {//用請求去獲取資源
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                Bitmap bitmap = response.getBitmap();//獲取資源
                imageView.setImageBitmap(bitmap);//綁定給imageView
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }
});

方式2

imageLoader.get(URL_IMG, ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher));//獲取資源並綁定給imageView,設置默認圖片、加載失敗圖片

當程序退出時,在onStop()中取消請求,

@Override
protected void onStop() {
        super.onStop();
        if (requestQueue != null){
            //取消請求
            requestQueue.cancelAll(TAG);
            requestQueue2.cancelAll(TAG);
        }
}

步驟2.1.2在此
1.工廠類,VolleyFactroy .java

public class VolleyFactroy {
    private RequestQueue requestQueue;
    private Context context;
    private MImgCache imgCache;

    private VolleyFactroy(Context context) {
        this.context = context;
        requestQueue = getRequestQueue();
        imgCache = new MImgCache();
    }

    private static VolleyFactroy instance;

    public static synchronized VolleyFactroy getInstance(Context context) {
        if (instance == null)
            instance = new VolleyFactroy(context);
        return instance;
    }

    public RequestQueue getRequestQueue(){
        if (requestQueue == null)
            requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        return requestQueue;
    }

    public <T> void addRequest(Request<T> request) {
        getRequestQueue().add(request);
    }

    public void cancelRequest(Object tag) {
        getRequestQueue().cancelAll(tag);
    }

    public MImgCache getImgCache() {
        return imgCache;
    }
}

2.圖片緩存類

public class MImgCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
    private static int MAX_SIZE = 10 * 1024 * 1024;//緩存大小

    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *                the maximum number of entries in the cache. For all other caches,
     *                this is the maximum sum of the sizes of the entries in this cache.
     */
    public MImgCache(int maxSize) {
        super(maxSize);
    }

    public MImgCache() {
        this(MAX_SIZE);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

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

3.使用工廠輔助創建imageLoader

ImageLoader imageLoader = new ImageLoader(requestQueue2,VolleyFactroy.getInstance(this).getImgCache());

附:MainActivity完整代碼

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    public static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=13812345678&key=daf8fa858c330b22e342c882bcbac622";
    public static final String URL_POST = "http://apis.juhe.cn/mobile/get ";
    public static final String URL_IMG = "http://img2.3lian.com/2014/f7/5/d/22.jpg";
    public static String TAG = "QL";
    private TextView textView;
    private TextView textView1;
    private RequestQueue requestQueue;
    private ImageView imageView;
    private RequestQueue requestQueue2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);
        textView1 = (TextView) findViewById(R.id.textView2);

        requestQueue = Volley.newRequestQueue(this);
        requestQueue2 = VolleyFactroy.getInstance(this).getRequestQueue();
//        get();
//        post();
        getImg();
    }

    public  void getImg(){
        imageView = (ImageView) findViewById(R.id.imageView);
        //方法二,自定義實例工廠和緩存類
        ImageLoader imageLoader = new ImageLoader(requestQueue2,VolleyFactroy.getInstance(this).getImgCache());
        imageLoader.get(URL_IMG, ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
    }

    public void getImg3(){
        //方法1
        ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }

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

            }
        });
        imageLoader.get(URL_IMG, ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
    }

    private void getImg2() {
        ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
            }
        });
        imageLoader.get(URL_IMG, new ImageLoader.ImageListener() {
            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                Bitmap bitmap = response.getBitmap();
                imageView.setImageBitmap(bitmap);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
    }

    private void getNetWorkImage() {
        NetworkImageView networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

        networkImageView.setDefaultImageResId(R.mipmap.ic_launcher);
        networkImageView.setErrorImageResId(R.mipmap.ic_launcher);
        networkImageView.setTag(TAG);
        networkImageView.setImageUrl(URL_IMG, new ImageLoader(requestQueue, new ImageLoader
                .ImageCache() {

            @Override
            public Bitmap getBitmap(String url) {
                return null;
            }

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

            }
        }));
    }

    public void get() {
        StringRequest request = new StringRequest(URL_GET, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                textView.setText(response.toString());
            }
        }, new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error) {
                textView1.setText(error.toString());
            }
        });
        request.setTag(TAG);
        requestQueue.add(request);
//        requestQueue2.add(request);
    }

    public  void post(){
        StringRequest request = new StringRequest(Request.Method.POST, URL_POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                textView.setText(response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView1.setText(error.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<>();
                map.put("phone", "18977921449");
                map.put("key", "daf8fa858c330b22e342c882bcbac622");
                return map;
            }
        };
        request.setTag(TAG);
        requestQueue.add(request);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (requestQueue != null){
            //取消請求
            requestQueue.cancelAll(TAG);
            requestQueue2.cancelAll(TAG);
        }
    }
}

工廠類方法在此部分的上面 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章