Sending a Simple Request

1.This lesson teaches you to

  1. Add the INTERNET Permission
  2. Use newRequestQueue  Volley.newRequestQueue示例
  3. Send a Request   RequestQueue发送请求的流程
  4. Cancel a Request 如何取消正在运行的请求,以及取消所有tag为xx的请求

VIDEO

  Volley: Easy, Fast Networking for Android

  At a high level, you use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.

  This lesson describes how to send a request using theVolley.newRequestQueue convenience method, which sets up a RequestQueue for you. See the next lesson, Setting Up a RequestQueue, for information on how to set up aRequestQueue yourself.

  This lesson also describes how to add a request to aRequestQueue and cancel a request.

2.Add the INTERNET Permission

  To use Volley, you must add the android.permission.INTERNET permission to your app's manifest. Without this, your app won't be able to connect to the network.

3.Use newRequestQueue

  Volley provides a convenience method Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue. For example:

 final TextView mTextView = (TextView) findViewById(R.id.text);
... // Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com"; // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(,));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

  Volley always delivers parsed responses on the main thread. Running on the main thread is convenient for populating UI controls with received data, as you can freely modify UI controls directly from your response handler, but it's especially critical to many of the important semantics provided by the library, particularly related to canceling requests.

See Setting Up a RequestQueue for a description of how to set up a RequestQueue yourself, instead of using the Volley.newRequestQueue convenience method.

4.Send a Request

  To send a request, you simply construct one and add it to the RequestQueue with add(), as shown above. Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.

  先从线程池,唤起一个线程,如果本地缓存可以服务,那么就返回数据,不可以就发出请求.然后将返回数据写入到缓存,解析数据并传给UI线程.

  When you call add(), Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parsse the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.

  Note that expensive operations like blocking I/O and parsing/decoding are done on worker threads. You can add a request from any thread, but responses are always delivered on the main thread.

  Figure 1 illustrates the life of a request:

  Figure 1. Life of a request.

5.Cancel a Request

  To cancel a request, call cancel() on your Request object. Once cancelled, Volley guarantees that your response handler will never be called. What this means in practice is that you can cancel all of your pending requests in your activity's onStop() method and you don't have to litter your response handlers with checks forgetActivity() == null, whether onSaveInstanceState() has been called already, or other defensive boilerplate.

  To take advantage of this behavior, you would typically have to track all in-flight requests in order to be able to cancel them at the appropriate time. There is an easier way: you can associate a tag object with each request. You can then use this tag to provide a scope of requests to cancel. For example, you can tag all of your requests with the Activity they are being made on behalf of, and call requestQueue.cancelAll(this) fromonStop(). Similarly, you could tag all thumbnail image requests in a ViewPager tab with their respective tabs and cancel on swipe to make sure that the new tab isn't being held up by requests from another one.

  Here is an example that uses a string value for the tag:

  1. Define your tag and add it to your requests.

     public static final String TAG = "MyTag";
    StringRequest stringRequest; // Assume this exists.
    RequestQueue mRequestQueue; // Assume this exists. // Set the tag on the request.
    stringRequest.setTag(TAG); // Add the request to the RequestQueue.
    mRequestQueue.add(stringRequest);
  2. In your activity's onStop() method, cancel all requests that have this tag.
     @Override
    protected void onStop () {
    super.onStop();
    if (mRequestQueue != null) {
    mRequestQueue.cancelAll(TAG);
    }
    }

  Take care when canceling requests. If you are depending on your response handler to advance a state or kick off another process, you need to account for this. Again, the response handler will not be called.

Volley HTTP库系列教程(2)Volley.newRequestQueue示例,发请求的流程,取消请求的更多相关文章

  1. Volley HTTP库系列教程(4)Volley内置的几种请求介绍及示例,StringRequest,ImageRequest,JsonObjectRequest

    Making a Standard Request Previous  Next   This lesson teaches you to Request a String 返回String Requ ...

  2. Volley HTTP库系列教程(5)自定义一个Volley请求

    Implementing a Custom Request Previous  Next This lesson teaches you to Write a Custom Request parse ...

  3. Volley HTTP库系列教程(3)自定义RequestQueue和编写单例RequestQueue示例

    Setting Up a RequestQueue Previous  Next This lesson teaches you to Set Up a Network and Cache Use a ...

  4. Volley HTTP库系列教程(1)简介及优点

    Transmitting Network Data Using Volley Get  started Dependencies and prerequisites Android 1.6 (API ...

  5. 利用百度词典API和Volley网络库开发的android词典应用

     关于百度词典API的说明,地址在这里:百度词典API介绍 关于android网络库Volley的介绍说明,地址在这里:Android网络通信库Volley 首先我们看下大体的界面布局!

  6. 【安卓网络请求开源框架Volley源码解析系列】初识Volley及其基本用法

    在安卓中当涉及到网络请求时,我们通常使用的是HttpUrlConnection与HttpClient这两个类,网络请求一般是比较耗时,因此我们通常会在一个线程中来使用,但是在线程中使用这两个类时就要考 ...

  7. webpack4 系列教程(十二):处理第三方JavaScript库

    教程所示图片使用的是 github 仓库图片,网速过慢的朋友请移步<webpack4 系列教程(十二):处理第三方 JavaScript 库>原文地址.或者来我的小站看更多内容:godbm ...

  8. python基础系列教程——Python3.x标准模块库目录

    python基础系列教程——Python3.x标准模块库目录 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata ...

  9. python基础系列教程——Python库的安装与卸载

    python基础系列教程——Python库的安装与卸载 2.1 Python库的安装 window下python2.python3安装包的方法 2.1.1在线安装 安装好python.设置好环境变量后 ...

随机推荐

  1. bzoj 3293 数学整理

    和1045一模一样,找到这道题的时候还愣了下神,最后发现样例都是 一样的,直接粘了1045的代码,具体题解看 http://www.cnblogs.com/BLADEVIL/p/3468729.htm ...

  2. LightOJ 1140 How Many Zeroes

    题意:写出一个给定区间的每个数,求出一共写了多少个零. 解法:数位DP,定义dp[len][flag][num]:len的定义为数位的长度,flag定义为前导0和没有前导0的两种状态,num定义为写的 ...

  3. 设计模式 - Template Method

    今天下午主要研究了设计模式中的Template Method(模版方法设计模式). 在Spring中,对各种O/RM进行了封装,比如对Hibernate有HibernateTemplate封装:对JD ...

  4. Orchard中文学习视频录制完成

    Orchard学习视频已登录百度传课: http://www.chuanke.com/3027295-124882.html http://pan.baidu.com/s/13zc0u 1.orcha ...

  5. Java获取项目中的路径 分类: Java Game 2014-08-14 10:17 122人阅读 评论(0) 收藏

    在项目中经常需要获取某个文件的路径: 在这里提供一些获取路径的方法.. 1.此种方式获取的路径,是当前类所在的路径: UserDAOTest.class.getResource("UserD ...

  6. RAID磁盘阵列学习笔记

    RAID是“Redundant Array of Independent Disk”的缩写,中文意思是独立冗余磁盘阵列.简单地解释,就是将N台硬盘通过RAID Controller(分Hardware ...

  7. .NET设计模式(15):结构型模式专题总结(转)

    摘要:结构型模式,顾名思义讨论的是类和对象的结构,它采用继承机制来组合接口或实现(类结构型模式),或者通过组合一些对象,从而实现新的功能(对象结构型模式).这些结构型模式,它们在某些方面具有很大的相似 ...

  8. tomcat与IIS在多IP服务器下的支持

    同一个服务器下,双IP(或更多IP),实现tomcat与IIS公用80端口. 操作其实也很简单的,首先禁用iis的套接字池,iis绑定一个ip,然后tomcat在绑定另一个ip,最后重启下服务器即可. ...

  9. close和shutdown的区别

    转的,没验证 close(sock_fd)会把sock_fd的内部计数器减1当sock_fd的内部计数器为0时, 才调用shutodwn(), 并最终释放文件描述符调用shutdown()只是进行了T ...

  10. APM 终端用户体验监控分析(上)

    一.前言 理解用户体验是从终端用户角度了解应用交付质量的关键,这是考量业务健康运转的潜在因素.捕获此类数据的方法各种各样,具体的实现途径由应用.基础设施架构以及管理者和管理过程决定. 二.终端用户监控 ...