1. 程式人生 > >volley框架的詳細使用

volley框架的詳細使用

Volley可以 自動排程網路請求 多個併發的網路連線 通過使用標準的HTTP快取機制保持磁碟和記憶體響應的一致 支援請求優先順序 支援取消請求的強大API,可以取消單個請求或多個 易於定製 健壯性:便於正確的更新UI和獲取資料 包含除錯和追蹤工具等優點。

Volley特別適合資料量不大但是通訊頻繁的場景。

2、新佈局程式碼中新增幾個按鈕,兩個圖片按鈕和一個textview用於顯示資料

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/volley_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="get請求" />

    <Button
        android:id="@+id/volley_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="post請求" />

    <Button
        android:id="@+id/volley_json"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="請求json資料請求" />

    <Button
        android:id="@+id/volley_imageRequest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="imageRequest載入圖片" />

    <Button
        android:id="@+id/volley_imageLader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="imageLader載入圖片" />

    <Button
        android:id="@+id/netWorkImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="netWorkImageView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text="顯示結果" />

    <ImageView
        android:id="@+id/volley_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip" />

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/volley_imageNet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5dip">

        <TextView
            android:id="@+id/volley_result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="" />

    </ScrollView>
</LinearLayout>
3、由於要顯示網路圖片,所以新增fresco,需要在build.gradle 中新增下面程式碼,並在需要在新建一個MyApplication類,記得在許可權中新增。還要新增網路許可權程式碼
compile 'com.facebook.fresco:fresco:0.12.0'
package com.example.apple.volley;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;

/**
 * Created by apple on 16/12/29.
 */

public class MyApplication extends Application {
    public MyApplication() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //Fresco初始化
        Fresco.initialize(getApplicationContext());
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.apple.volley">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
4、先實現get 請求,首先建立一個佇列,然後建立一個請求,將url傳進去,請求中有兩個方法,當正確接受資料時可以打印出來,錯誤時也可以顯示出來,最後新增到佇列中,這就完成了get請求。返回的資料可自己處理。
  /**
     * get
     */
    public void get(){
        //建立一個請求佇列
        requestQueue = Volley.newRequestQueue(MainActivity.this);
        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";

        StringRequest stringRequest =new StringRequest(url, new Response.Listener<String>() {
            //正確接收資料回撥
            @Override
            public void onResponse(String s) {

                try {
                    JSONObject jsonObject = new JSONObject(s);
                   // TestData testData= new Gson().fromJson(s, TestData.class);
                   // Log.e(TAG,"length="+jsonObject.getJSONObject("trailers").length());
                 //   for (int i = 0;i<jsonObject.getJSONObject("trailers").length();i++){
                        volley_result.setText(s);
                        Log.e(TAG,"s="+jsonObject.getJSONArray("trailers").get(0)+"\n");
                   // }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {//異常後的監聽資料
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);
            }
        });
        //將get請求新增到佇列中
        requestQueue.add(stringRequest);
    }

5、實現post請求,post請求跟get差不多,都要建立一個佇列,然後建立一個請求,再新增到佇列中,不同的是,需要在建立請求時宣告是POST,傳入引數時可以用Map,然後返回。
private void post(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);
        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                volley_result.setText(s);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String,String> map = new HashMap<>();
               // map.put("value1","param1");//傳入引數

                return map;
            }
        };

        //將post請求新增到佇列中
        requestQueue.add(stringRequest);
    }

6、json請求,跟上面基本一樣,但是如果資料格式外面時{}需要用JsonObjectRequest,如果時[]則要用JsonArrayRequest,返回的是JSONObject資料。
 private void json(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                //TestData data = new Gson().fromJson(String.valueOf(jsonObject),TestData.class);
                volley_result.setText(jsonObject.toString());
                Log.e(TAG,"data="+jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);

            }
        });

        //將建立的請求新增到佇列中
        requestQueue.add(jsonObjectRequest);
    }

7、載入圖片,也是需要那三步,但是是用ImageRequest。
 /**
     * 載入圖片
     */
    private void image(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        //第二個引數,第三個:寬高,第四個:圖片質量
        ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                //正確接收圖片
                volley_image.setImageBitmap(bitmap);
            }
        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_image.setImageResource(R.mipmap.ic_launcher);
            }
        });

        //將建立的請求新增到佇列中
        requestQueue.add(imageRequest);
    }
8、載入網路圖片,這個可以新建一個BitmapCache類用來快取圖片
private void imageLoader(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求

//        ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
//            @Override
//            public Bitmap getBitmap(String s) {
//                return null;
//            }
//
//            @Override
//            public void putBitmap(String s, Bitmap bitmap) {
//
//            }
//        });

        ImageLoader imageLoader = new ImageLoader(requestQueue,new BitmapCache());//帶快取

        //載入圖片
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        //載入不到,載入失敗
        ImageLoader.ImageListener imageLister = imageLoader.getImageListener(volley_imageNet,R.mipmap.ic_launcher,R.mipmap.ic_launcher);
        imageLoader.get(url,imageLister);
    }
package com.example.apple.volley.entity;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by apple on 16/12/29.
 * 圖片快取
 */

public class BitmapCache implements ImageLoader.ImageCache{

    private LruCache<String,Bitmap> mCache;

    public BitmapCache() {
        int maxSize = 10* 1024 *1024;//10m
        mCache = new LruCache<String,Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

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

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mCache.put(url,bitmap);
    }
}
10、載入網路圖片
/**
     * netWorkImageView
     */
    private void netWorkImageView(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個imageLoader
        ImageLoader imageLoader = new ImageLoader(requestQueue,new BitmapCache());

        //預設圖片設定
        volley_imageNet.setImageResource(R.mipmap.ic_launcher);

        //載入圖片
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        volley_imageNet.setImageURI(url,imageLoader);
    }
11、最後可以在stop中新增取消所有佇列

@Override
    protected void onStop() {
        super.onStop();
        //取消佇列裡所有的請求
        requestQueue.cancelAll(this);

    }

完整程式碼:

package com.example.apple.volley;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.apple.volley.entity.BitmapCache;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * JSON,影象等的非同步下載;
 網路請求的排序(scheduling)
 網路請求的優先順序處理
 快取
 多級別取消請求
 和Activity和生命週期的聯動(Activity結束時同時取消所有網路請求)
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button volley_get;
    private Button volley_post;
    private Button volley_json;
    private Button volley_imageRequest;
    private Button volley_imageLader;
    private Button netWorkImageView;
    private ImageView volley_image;
    private SimpleDraweeView volley_imageNet;
    private TextView volley_result;
    private final String TAG = "MainActivity";

    RequestQueue requestQueue;

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

        initView();
    }

    private void initView() {
        volley_get = (Button)findViewById(R.id.volley_get);
        volley_get.setOnClickListener(this);

        volley_post = (Button)findViewById(R.id.volley_post);
        volley_post.setOnClickListener(this);

        volley_json = (Button)findViewById(R.id.volley_json);
        volley_json.setOnClickListener(this);

        volley_imageRequest = (Button)findViewById(R.id.volley_imageRequest);
        volley_imageRequest.setOnClickListener(this);

        volley_imageLader = (Button)findViewById(R.id.volley_imageLader);
        volley_imageLader.setOnClickListener(this);

        netWorkImageView = (Button)findViewById(R.id.netWorkImageView);
        netWorkImageView.setOnClickListener(this);

        volley_image = (ImageView) findViewById(R.id.volley_image);

        volley_imageNet = (SimpleDraweeView) findViewById(R.id.volley_imageNet);

        volley_result = (TextView)findViewById(R.id.volley_result);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.volley_get://get請求

                get();

                break;

            case R.id.volley_post://post請求

                post();
                break;

            case R.id.volley_json://json請求 JsonObjectRequest{} JsonArrayRequest[]

                json();
                break;

            case R.id.volley_imageRequest://imageRequest載入圖片

                image();
                break;

            case R.id.volley_imageLader://imageLader載入圖片
                imageLoader();

                break;

            case R.id.netWorkImageView:
                    netWorkImageView();
                break;

            default:
                break;

        }
    }

    /**
     * get
     */
    public void get(){
        //建立一個請求佇列
        requestQueue = Volley.newRequestQueue(MainActivity.this);
        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";

        StringRequest stringRequest =new StringRequest(url, new Response.Listener<String>() {
            //正確接收資料回撥
            @Override
            public void onResponse(String s) {

                try {
                    JSONObject jsonObject = new JSONObject(s);
                   // TestData testData= new Gson().fromJson(s, TestData.class);
                   // Log.e(TAG,"length="+jsonObject.getJSONObject("trailers").length());
                 //   for (int i = 0;i<jsonObject.getJSONObject("trailers").length();i++){
                        volley_result.setText(s);
                        Log.e(TAG,"s="+jsonObject.getJSONArray("trailers").get(0)+"\n");
                   // }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {//異常後的監聽資料
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);
            }
        });
        //將get請求新增到佇列中
        requestQueue.add(stringRequest);
    }

    /**
     * post
     */
    private void post(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);
        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                volley_result.setText(s);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String,String> map = new HashMap<>();
               // map.put("value1","param1");//傳入引數

                return map;
            }
        };

        //將post請求新增到佇列中
        requestQueue.add(stringRequest);
    }

    /**
     * json
     */
    private void json(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求
        String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                //TestData data = new Gson().fromJson(String.valueOf(jsonObject),TestData.class);

                volley_result.setText(jsonObject.toString());


                Log.e(TAG,"data="+jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_result.setText("載入錯誤"+volleyError);

            }
        });

        //將建立的請求新增到佇列中
        requestQueue.add(jsonObjectRequest);
    }

    /**
     * 載入圖片
     */
    private void image(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        //第二個引數,第三個:寬高,第四個:圖片質量
        ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                //正確接收圖片
                volley_image.setImageBitmap(bitmap);
            }
        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volley_image.setImageResource(R.mipmap.ic_launcher);
            }
        });

        //將建立的請求新增到佇列中
        requestQueue.add(imageRequest);
    }

    /**
     * imageLoader
     */
    private void imageLoader(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個請求

//        ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
//            @Override
//            public Bitmap getBitmap(String s) {
//                return null;
//            }
//
//            @Override
//            public void putBitmap(String s, Bitmap bitmap) {
//
//            }
//        });

        ImageLoader imageLoader = new ImageLoader(requestQueue,new BitmapCache());//帶快取

        //載入圖片
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        //載入不到,載入失敗
        ImageLoader.ImageListener imageLister = imageLoader.getImageListener(volley_imageNet,R.mipmap.ic_launcher,R.mipmap.ic_launcher);
        imageLoader.get(url,imageLister);
    }

    /**
     * netWorkImageView
     */
    private void netWorkImageView(){
        //建立一個請求佇列
         requestQueue = Volley.newRequestQueue(MainActivity.this);

        //建立一個imageLoader
        ImageLoader imageLoader = new ImageLoader(requestQueue,new BitmapCache());

        //預設圖片設定
        volley_imageNet.setImageResource(R.mipmap.ic_launcher);

        //載入圖片
        String url = "http://img5.mtime.cn/mg/2016/12/26/164311.99230575.jpg";
        volley_imageNet.setImageURI(url,imageLoader);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消佇列裡所有的請求
        requestQueue.cancelAll(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
實現效果圖片和程式碼下載地址:http://download.csdn.net/detail/u011324501/9725043