Android筆記(六十二)網路架構volley

來源:互聯網
上載者:User

標籤:

什麼是Volley

       很多時候,我們的APP都需要用到網路技術,使用HTTP協議來發送接收資料,Google推出了一個網路架構——volley,該架構適合進行資料量不大,但通訊頻繁的網路操作。

       它的優點:

       (1)預設Android2.3及以上基於HttpURLConnection,2.3以下使用基於HttpClient;

       (2)符合Http 緩衝語義 的緩衝機制(提供了預設的磁碟和記憶體等緩衝);

       (3)請求隊列的優先順序排序;

       (4)提供多樣的取消機制;

       (5)提供簡便的圖片載入工具(其實圖片的載入才是我們最為看重的功能)

       它的缺點:

       不適合資料量大的傳輸,例如下載、視頻傳輸等

       首先擷取Volley的jar包,具體方法不贅述。

       https://android.googlesource.com/platform/frameworks/volley  

如何使用Volley

      最簡單的使用方法可以歸納為:

      1.建立一個請求隊列→2.建立一個請求→3.將請求加到隊列中

      就是這麼簡單!

StringRequest

      一個簡單的例子:

MainActivity.java

package com.example.volleydemo;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.Response.Listener;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {    private Button bt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bt = (Button) findViewById(R.id.bt);        bt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 定義一個請求隊列                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());                // 定義一個字串請求                // StringRequest的構造方法需要傳入三個參數,第一個參數是我們要請求的地址,第二個參數當我們的請求響應成功時候的回調,第三個參數是當我們請求失敗時候的回調                StringRequest sr = new StringRequest("http://www.baidu.com", new Listener<String>() {                    @Override                    public void onResponse(String response) {                        Log.d("TTTT", response);                    }                }, new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                        Log.d("TTTT", "串連出錯啦!!");                    }                });                // 將請求加入到隊列中                requestQueue.add(sr);            }        });    }}

activity_main.xml

<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="com.example.volleydemo.MainActivity" >    <Button        android:id="@+id/bt"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="click me" /></RelativeLayout>

       因為我們需要訪問網路,我們還需要添加INTERNET許可權,我們先不加試試,不加許可權,啟動並執行結果是:

      可以看到執行了onErrorResponse中內容

      我們加上許可權

    <uses-permission android:name="android.permission.INTERNET"/>

      運行結果:

      執行成功!Volley就是這麼簡單

JsonRequest

MainActivity.java

package com.example.volleydemo;import org.json.JSONObject;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {    private Button bt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bt = (Button) findViewById(R.id.bt);        bt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 定義一個請求隊列                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());                // 定義一個jsonobject請求                // JsonObjectRequest的構造方法需要傳入三個參數,第一個參數是我們要請求的地址,第二個參數是我們要傳遞給伺服器的參數,如果沒有,則為null,第三個參數當我們的請求響應成功時候的回調,第四個參數是當我們請求失敗時候的回調                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(                        "https://api.heweather.com/x3/weather?cityid=CN101010100&key=5d520eb089e646acb270521a7e387",                        null, new Response.Listener<JSONObject>() {                    public void onResponse(JSONObject response) {                        Log.d("TTTT", response.toString());                    }                }, new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                        // TODO Auto-generated method stub                    }                });                // 將請求加入到隊列中                requestQueue.add(jsonObjectRequest);            }        });    }}

       執行結果:成功!

ImageRequest

      ImageRequest的使用方法和之前的一樣,也是建立隊列,建立請求,把請求加入到隊列中,只不過ImageRequest的構造方法參數比較多,他們的含義分別為:

      url:請求地址

      listener:相應成功回調方法

      maxWidth:允許圖片的最大寬度,如果指定的網狀圖片寬度大於這裡的值,則會進行壓縮,如果為0則不進行壓縮

      maxHeight:允許圖片的最大高度,如果指定的網狀圖片高度大於這裡的值,則會進行壓縮,如果為0則不進行壓縮

      decodeConfig:執行圖片的顏色屬性Bitmap.Config下的幾個常量都可以在這裡使用

      errorListener:請求失敗回調方法

MainActivity.java

package com.example.volleydemo;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.ImageRequest;import com.android.volley.toolbox.Volley;import android.annotation.SuppressLint;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.View;import android.widget.Button;@SuppressLint("NewApi")public class MainActivity extends Activity {    private Button bt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bt = (Button) findViewById(R.id.bt);        bt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 定義一個請求隊列                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());                // 定義一個ImageRequest請求                ImageRequest imageRequest = new ImageRequest(                        "http://images.cnblogs.com/cnblogs_com/xs104/722323/o_pic.jpg",                        new Response.Listener<Bitmap>() {                    @Override                    public void onResponse(Bitmap response) {                        // 將請求返回的Bitmap對象轉換為Drawable對象                        Drawable drawable = new BitmapDrawable(response);                        // 將圖片設定為背景                        findViewById(R.id.layout).setBackground(drawable);                    }                }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {                    @Override                    public void onErrorResponse(VolleyError error) {                    }                });                // 將請求加入到隊列中                requestQueue.add(imageRequest);            }        });    }}

      運行結果:

Android筆記(六十二)網路架構volley

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.