Android進階-Volley-1.使用Volley

來源:互聯網
上載者:User

標籤:volley

參考連結:

http://www.codekk.com/open-source-project-analysis/detail/Android/grumoon/Volley%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90

 

Volley-Demo:

https://github.com/android-cn/android-open-project-demo/tree/master/volley-demo

 

1.      匯入Eclipse

將volley-demo(.\android-open-project-demo-master\volley-demo)匯入eclipse後:Eclipse->File->Import->ExistingAndroid Code Into Workspace。匯入後是一個HomeActivity,且會出現一堆R cannot be resolved to a variable的錯誤,重啟一下Eclipse即可

2.      學習volley-demo

2.1   使用StringRequest

以下是StringRequest的發送按鈕的監聽器代碼:

btnSend.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (StringUtil.isEmpty(etUrl.getText().toString())) {ToastUtil.showToast(getActivity(), "請輸入請求地址");return;}//請求之前,先取消之前的請求(取消還沒有進行完的請求)VolleyUtil.getQueue(getActivity()).cancelAll(this);tvResult.setText("");StringRequest request = new StringRequest(StringUtil.preUrl(etUrl.getText().toString().trim()),new Listener<String>() {@Overridepublic void onResponse(String response) {tvResult.setText(response);}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {ToastUtil.showToast(getActivity(), getResources().getString(R.string.request_fail_text));}});//請求加上Tag,用於取消請求request.setTag(this);VolleyUtil.getQueue(getActivity()).add(request);}});

從代碼中可以看出其主要是建立了一個StringRequest,然後通過add函數加入了請求隊列RequestQueue中。

接下來看StringRequest的建構函式:

public class StringRequest extends Request<String> {。。。public StringRequest(String url, Listener<String> listener, ErrorListener errorListener);。。。}

其中Request是一個抽象類別,Listener為介面。Request有建構函式:

public Request(int method, String url, Response.ErrorListener listener);public Request(String url, Response.ErrorListener listener) {        this(Method.DEPRECATED_GET_OR_POST, url, listener);    }

Listener中有函數:

public voidonResponse(T response);

當系統將StringRequest處理完成後會回調該函數。本demo中系統回調onResponse,將收到的資料顯示在TextView上。

 

3.      小結

使用Volley很簡單,過程可分為兩步:

  1. 建立請求隊列RequestQueue rq = new Volley.newRequestQueue()
  2. 建立請求XXRequest,然後將請求排入佇列rq中:rq.add(XXRequest);

今天先瞭解Volley的初步使用,下次將對Volley源碼進行詳細分析







Android進階-Volley-1.使用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.