volley7--NetworkDispatcher从网络中获取数据
源码:
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.android.volley; import android.annotation.TargetApi;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Process;
import android.os.SystemClock; import java.util.concurrent.BlockingQueue; /**
* Provides a thread for performing network dispatch from a queue of requests.
*
* Requests added to the specified queue are processed from the network via a
* specified {@link Network} interface. Responses are committed to cache, if
* eligible, using a specified {@link Cache} interface. Valid responses and
* errors are posted back to the caller via a {@link ResponseDelivery}.
*/
public class NetworkDispatcher extends Thread {
/** The queue of requests to service. */
private final BlockingQueue<Request<?>> mQueue;
/** The network interface for processing requests. */
private final Network mNetwork;
/** The cache to write to. */
private final Cache mCache;
/** For posting responses and errors. */
private final ResponseDelivery mDelivery;
/** Used for telling us to die. */
private volatile boolean mQuit = false; /**
* Creates a new network dispatcher thread. You must call {@link #start()}
* in order to begin processing.
*
* @param queue Queue of incoming requests for triage
* @param network Network interface to use for performing requests
* @param cache Cache interface to use for writing responses to cache
* @param delivery Delivery interface to use for posting responses
*/
public NetworkDispatcher(BlockingQueue<Request<?>> queue,
Network network, Cache cache,
ResponseDelivery delivery) {
mQueue = queue;
mNetwork = network;
mCache = cache;
mDelivery = delivery;
} /**
* Forces this dispatcher to quit immediately. If any requests are still in
* the queue, they are not guaranteed to be processed.
*/
public void quit() {
mQuit = true;
interrupt();
} @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void addTrafficStatsTag(Request<?> request) {
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
} @Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Request<?> request;
while (true) {
long startTimeMs = SystemClock.elapsedRealtime();
// release previous request object to avoid leaking request object when mQueue is drained.
request = null;
try {
// Take a request from the queue.
request = mQueue.take();
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
} try {
request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the
// network request.
if (request.isCanceled()) {
request.finish("network-discard-cancelled");
continue;
} addTrafficStatsTag(request); // Perform the network request.
NetworkResponse networkResponse = mNetwork.performRequest(request);
request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already,
// we're done -- don't deliver a second identical response.
if (networkResponse.notModified && request.hasHadResponseDelivered()) {
request.finish("not-modified");
continue;
} // Parse the response here on the worker thread.
Response<?> response = request.parseNetworkResponse(networkResponse);
request.addMarker("network-parse-complete"); // Write to cache if applicable.
// TODO: Only update cache metadata instead of entire record for 304s.
if (request.shouldCache() && response.cacheEntry != null) {
mCache.put(request.getCacheKey(), response.cacheEntry);
request.addMarker("network-cache-written");
} // Post the response back.
request.markDelivered();
mDelivery.postResponse(request, response);
} catch (VolleyError volleyError) {
volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
parseAndDeliverNetworkError(request, volleyError);
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
VolleyError volleyError = new VolleyError(e);
volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
mDelivery.postError(request, volleyError);
}
}
} private void parseAndDeliverNetworkError(Request<?> request, VolleyError error) {
error = request.parseNetworkError(error);
mDelivery.postError(request, error);
}
}
NetworkDispatcher
volley7--NetworkDispatcher从网络中获取数据的更多相关文章
- Android 从网络中获取数据时 产生部分数据乱码的解决
产生部分数据乱码的解决 标签: android部分中文乱码 2014-04-12 23:24 12366人阅读 评论(10) 收藏 举报 分类: [Android 基础](15) 版权声明:本文为博主 ...
- Thymeleaf+SpringMVC,如何从模板中获取数据
Thymeleaf+SpringMVC,如何从模板中获取数据 在一个典型的SpringMVC应用中,带@Controller注解的类负责准备数据模型Map的数据和选择一个视图进行渲染.这个模型Map对 ...
- 从网络中获取图片显示到Image控件并保存到磁盘
一.从网络中获取图片信息: /// <summary> /// 获取图片 /// </summary> /// <param name="url"&g ...
- hive从查询中获取数据插入到表或动态分区
Hive的insert语句能够从查询语句中获取数据,并同时将数据Load到目标表中.现在假定有一个已有数据的表staged_employees(雇员信息全量表),所属国家cnty和所属州st是该表的两 ...
- 哪种方式更适合在React中获取数据?
作者:Dmitri Pavlutin 译者:小维FE 原文:dmitripavlutin.com 国外文章,笔者采用意译的方式,以保证文章的可读性. 当执行像数据获取这样的I/O操作时,你必须发起获取 ...
- Django Form 实时从数据库中获取数据
修改 models.py 添加 class UserType(models.Model): caption = models.CharField(max_length=32) 执行命令,生成数据库 p ...
- SpringMVC从Request域中获取数据
SpringMVC从Request域中获取数据的三种方式 SpringMVC环境自行搭建, 约定存在如下目录和文件:/WEB-INF/pages/success.jsp 方式一:传入Model对象 前 ...
- SQL语句的使用,SELECT - 从数据库表中获取数据 UPDATE - 更新数据库表中的数据 DELETE - 从数据库表中删除数据 INSERT INTO - 向数据库表中插入数据
SQL DML 和 DDL 可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL). SQL (结构化查询语言)是用于执行查询的语法. 但是 SQL 语言也包含用于更新. ...
- Android从网络中获取xml文件并解析数据
public class XmlwebData { @SuppressLint("UseValueOf") public static List<Person> get ...
随机推荐
- springcloud(四)-Eureka Server集群
Eureka Server的高可用 这一节我们接着上一节说. 有分布式应用开发经验的朋友应该发现,前文编写的单节点Eureka Server并不适合线上生产环境.Eureka Client会定时连接E ...
- Openerp 添加修改报表
Report Designer 模块在生成新报表的时候是有BUG的不建议直接使用,不过我们也可以通过该插件再写简单的代码来实现新添加报表,插件安装成功后我们可以按照下列方法来添加报表 OpenERP ...
- ToolkitScriptManager vs. ScriptManager 关于“只能向页面中添加 ScriptManager 的一个实例”讨论
在使用ASP.NET设计AJAX功能网页时,需要首先声明ToolkitScriptManager或者ScriptManager控件,这些全局的脚本核心控制,然后才能使用众多的AJAX控件.如果没有创建 ...
- ubuntu设置root权限默认密码
1.默认root密码是随机的,即每次开机都有一个新的root密码.我们可以在终端输入命令 sudo passwd,然后输入当前用户的密码2.终端会提示我们输入新的密码并确认,此时的密码就是root新密 ...
- JS写游戏
最近在看萧井陌的视频.感觉一些东西挺有意思的,尤其是解决问题的过程,以及一个好程序应该改进的地方. 萧大的GITHUB:github.com/guaxiao/gua.game.js 视频:https: ...
- 深度学习(十五) TextCNN理解
以下是阅读TextCNN后的理解 步骤: 1.先对句子进行分词,一般使用“jieba”库进行分词. 2.在原文中,用了6个卷积核对原词向量矩阵进行卷积. 3.6个卷积核大小:2个4*6.2个3*6和2 ...
- Struts1原理解析
1.浏览器发送http请求->web服务器. 2.web服务器将 请求进行解析. 3.web服务器解析后将请求转发给ActionServelet(总队长). 3.查询struts-config. ...
- getSqlMapClientTemplate().insert()方法的返回值问题
insert方法的返回值 今天碰到一个问题,就是关于ibatis的insert方法的返回值的问题.在网上找了很多例子,自己也亲自试了一下. 最后得出结论:insert方法返回的是在表中插入记录 ...
- springmvc 权限 测试版
参考博文 https://blog.csdn.net/u011277123/article/details/68940939 1.Listener加载权限信息 2.interceptor验证权限 测试 ...
- 注解完成spring json返回数据格式配置
import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.module.Simp ...