volley7–NetworkDispatcher从网络中获取数据[通俗易懂]

volley7–NetworkDispatcher从网络中获取数据

大家好,又见面了,我是全栈君。

源码:

volley7--NetworkDispatcher从网络中获取数据[通俗易懂]
volley7--NetworkDispatcher从网络中获取数据[通俗易懂]

  1 /*
  2  * Copyright (C) 2011 The Android Open Source Project
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package com.android.volley;
 18 
 19 import android.annotation.TargetApi;
 20 import android.net.TrafficStats;
 21 import android.os.Build;
 22 import android.os.Process;
 23 import android.os.SystemClock;
 24 
 25 import java.util.concurrent.BlockingQueue;
 26 
 27 /**
 28  * Provides a thread for performing network dispatch from a queue of requests.
 29  *
 30  * Requests added to the specified queue are processed from the network via a
 31  * specified {@link Network} interface. Responses are committed to cache, if
 32  * eligible, using a specified {@link Cache} interface. Valid responses and
 33  * errors are posted back to the caller via a {@link ResponseDelivery}.
 34  */
 35 public class NetworkDispatcher extends Thread {
 36     /** The queue of requests to service. */
 37     private final BlockingQueue<Request<?>> mQueue;
 38     /** The network interface for processing requests. */
 39     private final Network mNetwork;
 40     /** The cache to write to. */
 41     private final Cache mCache;
 42     /** For posting responses and errors. */
 43     private final ResponseDelivery mDelivery;
 44     /** Used for telling us to die. */
 45     private volatile boolean mQuit = false;
 46 
 47     /**
 48      * Creates a new network dispatcher thread.  You must call {@link #start()}
 49      * in order to begin processing.
 50      *
 51      * @param queue Queue of incoming requests for triage
 52      * @param network Network interface to use for performing requests
 53      * @param cache Cache interface to use for writing responses to cache
 54      * @param delivery Delivery interface to use for posting responses
 55      */
 56     public NetworkDispatcher(BlockingQueue<Request<?>> queue,
 57             Network network, Cache cache,
 58             ResponseDelivery delivery) {
 59         mQueue = queue;
 60         mNetwork = network;
 61         mCache = cache;
 62         mDelivery = delivery;
 63     }
 64 
 65     /**
 66      * Forces this dispatcher to quit immediately.  If any requests are still in
 67      * the queue, they are not guaranteed to be processed.
 68      */
 69     public void quit() {
 70         mQuit = true;
 71         interrupt();
 72     }
 73 
 74     @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
 75     private void addTrafficStatsTag(Request<?> request) {
 76         // Tag the request (if API >= 14)
 77         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
 78             TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
 79         }
 80     }
 81 
 82     @Override
 83     public void run() {
 84         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
 85         Request<?> request;
 86         while (true) {
 87             long startTimeMs = SystemClock.elapsedRealtime();
 88             // release previous request object to avoid leaking request object when mQueue is drained.
 89             request = null;
 90             try {
 91                 // Take a request from the queue.
 92                 request = mQueue.take();
 93             } catch (InterruptedException e) {
 94                 // We may have been interrupted because it was time to quit.
 95                 if (mQuit) {
 96                     return;
 97                 }
 98                 continue;
 99             }
100 
101             try {
102                 request.addMarker("network-queue-take");
103 
104                 // If the request was cancelled already, do not perform the
105                 // network request.
106                 if (request.isCanceled()) {
107                     request.finish("network-discard-cancelled");
108                     continue;
109                 }
110 
111                 addTrafficStatsTag(request);
112 
113                 // Perform the network request.
114                 NetworkResponse networkResponse = mNetwork.performRequest(request);
115                 request.addMarker("network-http-complete");
116 
117                 // If the server returned 304 AND we delivered a response already,
118                 // we're done -- don't deliver a second identical response.
119                 if (networkResponse.notModified && request.hasHadResponseDelivered()) {
120                     request.finish("not-modified");
121                     continue;
122                 }
123 
124                 // Parse the response here on the worker thread.
125                 Response<?> response = request.parseNetworkResponse(networkResponse);
126                 request.addMarker("network-parse-complete");
127 
128                 // Write to cache if applicable.
129                 // TODO: Only update cache metadata instead of entire record for 304s.
130                 if (request.shouldCache() && response.cacheEntry != null) {
131                     mCache.put(request.getCacheKey(), response.cacheEntry);
132                     request.addMarker("network-cache-written");
133                 }
134 
135                 // Post the response back.
136                 request.markDelivered();
137                 mDelivery.postResponse(request, response);
138             } catch (VolleyError volleyError) {
139                 volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
140                 parseAndDeliverNetworkError(request, volleyError);
141             } catch (Exception e) {
142                 VolleyLog.e(e, "Unhandled exception %s", e.toString());
143                 VolleyError volleyError = new VolleyError(e);
144                 volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
145                 mDelivery.postError(request, volleyError);
146             }
147         }
148     }
149 
150     private void parseAndDeliverNetworkError(Request<?> request, VolleyError error) {
151         error = request.parseNetworkError(error);
152         mDelivery.postError(request, error);
153     }
154 }

NetworkDispatcher

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/108121.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 与运算(&)、或运算(|)、异或运算(^)、进制转换

    与运算(&)、或运算(|)、异或运算(^)、进制转换参加运算的两个对象,按二进制位进行运算。进制转换地址:http://tool.oschina.net/hexconvert/一:与运算符(&)预算规则:0&0=0;0&1=0;1&0=0;1&1=1即:两个同时为1,结果为1,否则为0例如:3&5十进制3转为二进制的3:00000011十进制5转为二进制的5:0000…

    2022年5月29日
    41
  • Python怎么输入小数和整数_python输入非负整数

    Python怎么输入小数和整数_python输入非负整数python匹配整数或者小数(包括正数和负数)(简单易懂,代码可以直接运行)*这个实验算是五个正则表达式里面最难的的哪一个了,?是正则表达式里面贪婪与非贪婪的概念,有?则-?可有可无,刚好可以用于判断正数和负数,.在正则表达式里面表示的是任意字符(空格除外),因此如果要想表示小数点,需要加上以恶搞转义字符\,而区分整数和小数这两种情况,则需要加上一个|符号,表示前面的字符出现0次一次,+表示前面的字符出现1次以上#匹配整数或者小数num=’3333.3333’sss=re.search(r

    2022年9月1日
    3
  • vs code必备插件_手机flash player插件

    vs code必备插件_手机flash player插件基础必备插件:1、ViewInBrowser在浏览器里预览网页必备。2、vscode-icons改变编辑器里面的文件图标。个人比较稀饭这个,其他的你们可以自行选择。3、SublimeTextKeymapandSettingsImporter这个名字挺长,说白了就是sublime的快捷键插件。由于以前我是用sublime这款编辑器的,所以换成vscode之后没有su…

    2022年9月21日
    8
  • 通用目标检测_ug目标体完全处于工具体内部

    通用目标检测_ug目标体完全处于工具体内部睿智的目标检测-番外篇——数据增强在目标检测中的应用学习前言数据增强做了什么学习前言数据增强是非常重要的提高目标检测算法鲁棒性的手段,学习一下对身体有好处!数据增强做了什么…

    2022年10月10日
    3
  • 【转载】lvs为何不能完全替代DNS轮询

    【转载】lvs为何不能完全替代DNS轮询

    2021年11月20日
    54
  • Java微服务下的分布式事务介绍及其解决方案

    Java微服务下的分布式事务介绍及其解决方案1.前言1.由于最近在学习springcloud的项目,现在互联网下,分布式,微服务横行,难免会遇到分布式下的事务问题,这是一个难点,也是面试经常问的,别面试官一看你简历,都是微服务项目,问你了解啥是分布式事务不,你来句没有,这就很尴尬了,当然微服务下可能没有分布式事务,但是很多场景是需要分布式事务的,下面我就来介绍下什么是分布式事务,和分布式事务的解决方案2问题描述在介绍分布式事务…

    2022年6月14日
    28

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号