簡單迅捷的Android網絡模塊范例:Volley

jopen 10年前發布 | 41K 次閱讀 Volley Android開發 移動開發

Volley 是一個提供給 Android 應用非常易用的網絡庫,更好的是這個庫還加快了網絡訪問速度。本文會總覽Volley庫的主要功能,包括工作原理、常見工作模式以及如何使用該庫從網絡上并行加載縮略圖到應用ListView中的流程。

Volley是 AsyncTask 的絕佳替代品。對于Android開發者來說,為了做好ListView和網絡服務請求我們在AsyncTask上花了太多的時間。最近,我讀了一篇關于AsyncTask非常棒的文章,我建議每一個 Android 開發者都去讀一下+Fré Dumazy “Dark Side of AsyncTask”。AsyncTask 簡直成為了所有項目中的冗余。多虧了Volley 這個框架,現在我們可以有效地減少在 AsyncTasks上花費的編碼時間和精力了。

這篇文章演示了一個非常簡單的 Volley的示例。例子中的VolleyTest 應用會從Yahoo Pipe上獲取 JSON 文章數據并且顯示在 ListView 中。

簡單迅捷的Android網絡模塊范例:Volley

簡單迅捷的Android網絡模塊范例:Volley

第一步: 從 Git 倉庫把 Vollery 庫克隆下來

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

第二步: 在 Android Studio 中新建一個叫 “VolleyTest” 的項目

第三步: 將 Volley 的庫源文件拷貝到 “VolleyTest”的項目中,在這里復制源碼是最安全和簡單的方法。

簡單迅捷的Android網絡模塊范例:Volley

第四步: 在 AndroidManifest.xml 中添加網絡權限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="14" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.kpbird.volleytest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

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

</manifest></pre>

第五步: 在 activity_main.xml 中添加一個 ListView

<RelativeLayout xmlns:android="

<ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>

</RelativeLayout></pre>

第六步: 為 ListView 的行布局新建一個“row_listview.xml”

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/txtTitle" android:layout_gravity="left|center_vertical"/>
<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/txtDesc" android:layout_gravity="left|center_vertical" android:textColor="#929292"
        android:minLines="2" android:ellipsize="end" android:maxLines="2"/>
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/txtDate" android:layout_gravity="left|center_vertical" android:textColor="#d6d6d6"/>

</LinearLayout></pre>

第七步: 把如下代碼添加到 MainActivity.java 文件中
通過 Volley 去請求網絡需要分三步。
1、通過 Volley 類來新建一個新的請求隊列:

private RequestQueue mRequestQueue;
.
.
.
mRequestQueue = Volley.newRequestQueue(this);

2、新建一個 JsonObjectRequest 對象,并且設置好各項具體參數,比如url、http method以及監聽結果的listeners

JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG,response.toString());
                parseJSON(response);
                va.notifyDataSetChanged();
                pd.dismiss();
;            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG,error.getMessage());
            }
        });

3、將JsonObjectRequest添加到 JsonObjectRequest中:

mRequestQueue.add(jr);

下面的代碼是帶有Adapter,以及Model的完整代碼,為了方便閱讀我把所有的類都放到了一個Java文件中。

package com.kpbird.volleytest;

import android.app.ProgressDialog; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; 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.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends Activity {

private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lf = LayoutInflater.from(this);


    arrNews = new ArrayList<NewsModel>();
    va = new VolleyAdapter();

    lstView = (ListView) findViewById(R.id.listView);
    lstView.setAdapter(va);
    mRequestQueue =  Volley.newRequestQueue(this);
    String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
    pd = ProgressDialog.show(this,"Please Wait...","Please Wait...");
    try{
        Thread.sleep(2000);
    }catch(Exception e){

        }
    JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.i(TAG,response.toString());
            parseJSON(response);
            va.notifyDataSetChanged();
            pd.dismiss();

; } },new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.i(TAG,error.getMessage()); } }); mRequestQueue.add(jr);

}

private void parseJSON(JSONObject json){
    try{
        JSONObject value = json.getJSONObject("value");
        JSONArray items = value.getJSONArray("items");
        for(int i=0;i<items.length();i++){

                JSONObject item = items.getJSONObject(i);
                NewsModel nm = new NewsModel();
                nm.setTitle(item.optString("title"));
                nm.setDescription(item.optString("description"));
                nm.setLink(item.optString("link"));
                nm.setPubDate(item.optString("pubDate"));
                arrNews.add(nm);
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }


}


class NewsModel{
    private String title;
    private String link;
    private String description;
    private String pubDate;

    void setTitle(String title) {
        this.title = title;
    }

    void setLink(String link) {
        this.link = link;
    }

    void setDescription(String description) {
        this.description = description;
    }

    void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    String getLink() {
        return link;
    }

    String getDescription() {
        return description;
    }

    String getPubDate() {
        return pubDate;
    }

    String getTitle() {

        return title;
    }
}


class VolleyAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return arrNews.size();
    }

    @Override
    public Object getItem(int i) {
        return arrNews.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder vh ;
       if(view == null){
           vh = new ViewHolder();
           view = lf.inflate(R.layout.row_listview,null);
           vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
           vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
           vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
           view.setTag(vh);
      }
        else{
           vh = (ViewHolder) view.getTag();
       }

        NewsModel nm = arrNews.get(i);
        vh.tvTitle.setText(nm.getTitle());
        vh.tvDesc.setText(nm.getDescription());
        vh.tvDate.setText(nm.getPubDate());
        return view;
    }

     class  ViewHolder{
        TextView tvTitle;
         TextView tvDesc;
         TextView tvDate;

    }

}

}</pre>

你也可以從 Github 上獲取完整代碼: https://github.com/kpbird/volley-example

原文鏈接: kpbird   翻譯: 伯樂在線 - zerob13
譯文鏈接: http://blog.jobbole.com/71078/

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!