Volley framework introduction, volley framework

Source: Internet
Author: User
Tags epoch time

Volley framework introduction, volley framework
I. Introduction

Although many great gods and masters have already posted similar posts on the Internet, as a newcomer, you must follow the imitation path and think more than that. Therefore, you must take notes from the great gods, recording your understanding is the only way for a cainiao to succeed. As the signature says, record your own experience, and enjoy your youth with no regrets. Let's get down to the truth.

2. What is Volley?

Volley is Google's Android Asynchronous Network request framework and image loading framework.

Iii. Volley's main features

(1). Strong scalability. Volley is mostly based on interface design and is highly configurable.
(2). To a certain extent, it complies with Http specifications, including response code (2xx, 3xx, 4xx, 5xx), Request Header Processing, and Cache Mechanism support. Retry and priority definition are also supported.
(3) by default, Android2.3 and above are implemented based on HttpURLConnection and HttpClient under 2.3. The differences and advantages of the two are described in 4.2.1 Volley.
(4) provides a simple image loading tool.

Iv. Overall volley Design


From the network. As shown in, volley uses two Diapatch threads to continuously retrieve requests from RequestQueue. One of the two data acquisition interfaces, Cache or Network, is called based on whether the request has been cached, the request data is obtained from the memory cache or the server, and then sent to ResponseDelivery for Result Distribution and callback processing.

V. Concepts in volley

  • Volley: the API exposed by Volley, through newRequestQueue (...) Function to create and start a request queue RequestQueue.
  • Request: the abstract class of a Request. StringRequest, JsonRequest, and ImageRequest are all subclasses of StringRequest, indicating certain types of requests.
  • RequestQueue: indicates the Request queue, which contains a CacheDispatcher (the scheduling thread used to process cached requests) and a NetworkDispatcher array (used to process the scheduling thread that uses network requests ), A ResponseDelivery (return Result Distribution interface). When started using the start () function, CacheDispatcher and NetworkDispatchers are started.
  • CacheDispatcher: A thread used to schedule and process cached requests. After the service is started, requests are continuously processed from the cache Request queue. If the queue is empty, the requests are waiting. After the request is processed, the results are passed to ResponseDelivery for subsequent processing. When the results are not cached, the cache is invalid, or the cache needs to be refreshed, the request must be rescheduled to NetworkDispatcher.
  • NetworkDispatcher: A thread used to schedule and process requests that go through the network. After the service is started, requests are continuously processed from the network Request queue. If the queue is empty, the requests are waiting. After the request is processed, the results are passed to ResponseDelivery for subsequent processing, and determine whether the results need to be cached.
  • ResponseDelivery: Return Result Distribution interface. Currently, only ExecutorDelivery-based handler-based input parameters are distributed in the corresponding thread.
  • HttpStack: process Http requests and return the request results. Currently, Volley has HurlStack Based on HttpURLConnection and HttpClientStack Based on Apache HttpClient.
  • Network: Call HttpStack to process the request, and convert the result to the NetworkResponse processed by ResponseDelivery.
  • Cache: Cache request results. Volley uses the sdcard-based DiskBasedCache by default. After obtaining the request result, NetworkDispatcher determines whether the request needs to be stored in the Cache. CacheDispatcher retrieves the Cache result from the Cache.
Vi. volley request processing Flowchart
From the network. 7. volley class diagram to better understand volley, class diagram is an indispensable reference diagram.
VIII. volley Engineering Structure

Volley is an open-source project, and its engineering structure is shown in. 9. Introduction to core functions
  • Volley. java
(1). Main Functions
Volley. java has two overloaded static methods.
public static RequestQueue newRequestQueue(Context context)public static RequestQueue newRequestQueue(Context context, HttpStack stack)


The implementation of the first method calls the second method, and the parameter of passing HttpStack is null.
In the second method, if the HttpStatck parameter is null, if the system is in Gingerbread and later (that is, API Level> = 9), The HurlStack Based on HttpURLConnection is used. If it is smaller than 9, httpClientStack Based on HttpClient is used.
if (stack == null) {    if (Build.VERSION.SDK_INT >= 9) {        stack = new HurlStack();    } else {        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));    }}
HttpStack is obtained, and then a BasicNetwork is constructed to represent the Network.
Then construct a Disk-based implementation DiskBasedCache that represents the Cache.
Finally, the Network object and Cache object are passed in to build a RequestQueue, start the RequestQueue, and return.
Network network = new BasicNetwork(stack);RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);queue.start();return queue;
Generally, the default Implementation of Volly. newRequestQueue (context) is used to construct RequestQueue.
The source code shows that we can build a custom RequestQueue without using the Volley tool class, use the custom HttpStatck, use the custom Network implementation, and use the custom Cache implementation to construct the RequestQueue.
(2) How to Choose HttpURLConnection and AndroidHttpClient (HttpClient encapsulation) and the causes:
Before Froyo (2.2), there was a major Bug in HttpURLConnection. Calling the close () function will affect the connection pool, resulting in invalid connection reuse. Therefore, keepAlive needs to be disabled when using HttpURLConnection before Froyo.
In addition, gzip compression is enabled by default in Gingerbread (2.3) HttpURLConnection to improve HTTPS performance. Ice Cream Sandwich (4.0) HttpURLConnection supports request result caching.
In addition, the HttpURLConnection API is relatively simple. Therefore, for Android, we recommend that you use HttpURLConnection after 2.3. We recommend that you use AndroidHttpClient before.
  • Request. java
Represents an abstract class of a network request. We construct a non-Abstract subclass (StringRequest, JsonRequest, ImageRequest, or custom) object of the Request class, and add it to RequestQueue to complete a network Request operation.
Volley supports eight Http request methods: GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, and PATCH.
The Request class contains the Request url, Request method, Request Header, Request Body, and Request priority.
Because it is an abstract class, the subclass must override two methods.
abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
Subclass override this method to convert the native byte content returned by the network to an appropriate type. This method will be called in the work thread.
abstract protected void deliverResponse(T response);
Subclass override this method, which will be parsed into appropriate types of content and passed to their listener callback.
The following two methods are often overwritten:
public byte[] getBody()
Override this method to construct the Body content for POST, PUT, and PATCH requests.
protected Map<String, String> getParams()
If the above getBody function is not overwritten, the return values of this method will be encoded by the key and value respectively and assembled into bytecode as the Body content.
  • RequestQueue. java
Core class of the Volley framework, which adds Request to a running RequestQueue to complete Request operations.
(1). Main member variables
Two priority-based Request queues, cache Request queues, and network Request queues are maintained in RequestQueue.
Requests placed in the cache Request queue get data through the cache; requests placed in the network Request queue get data through the network.
private final PriorityBlockingQueue<Request<?>> mCacheQueue = new PriorityBlockingQueue<Request<?>>();private final PriorityBlockingQueue<Request<?>> mNetworkQueue = new PriorityBlockingQueue<Request<?>>();
A collection of ongoing and unfinished requests is maintained.
private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>();
A set of waiting requests is maintained. If a request is being processed and can be cached, subsequent requests with the same url will enter the waiting queue.
private final Map<String, Queue<Request<?>>> mWaitingRequests = new HashMap<String, Queue<Request<?>>>();
(2). Start the queue
After the RequestQueue is created, call the start method to start the queue.
/** * Starts the dispatchers in this queue. */public void start() {    stop();  // Make sure any currently running dispatchers are stopped.    // Create the cache dispatcher and start it.    mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);    mCacheDispatcher.start();    // Create network dispatchers (and corresponding threads) up to the pool size.    for (int i = 0; i < mDispatchers.length; i++) {        NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,                mCache, mDelivery);        mDispatchers[i] = networkDispatcher;        networkDispatcher.start();    }}
In the start method, start a cache scheduling thread CacheDispatcher and n network scheduling threads NetworkDispatcher. Here n is 4 by default, so there is room for optimization, for example, you can calculate a more appropriate number of concurrent tasks based on the number of CPU cores and the network type.
The cache scheduling thread constantly extracts requests from the cache Request queue for processing, and the network scheduling thread continuously extracts requests from the network Request queue for processing.
(3). Add request
public <T> Request<T> add(Request<T> request);
The flowchart is as follows:

(4). The request is complete.
void finish(Request<?> request)
Request ended
(1) first, remove the request from the in-progress request set mCurrentRequests.
(2 ). then, you can check whether a waiting request exists in the mWaitingRequests. If yes, the waiting queue is removed and all requests in the waiting queue are added to the cache Request queue, let the cache request processing thread CacheDispatcher automatically process the request.
(5). request cancellation
public void cancelAll(RequestFilter filter)public void cancelAll(final Object tag)
Cancels all eligible requests in the current request set.
The filter parameter indicates that the request to be canceled can be filtered according to the custom filter.
Tag indicates that the Request is canceled according to the tag set in Request. setTag. For example, the Request belongs to an Activity.

  • CacheDispatcher. java
A thread is used to schedule and process cached requests. After the service is started, requests are continuously processed from the cache Request queue. If the queue is empty, the requests are waiting. After the request is processed, the results are passed to ResponseDelivery for subsequent processing. When the results are not cached, the cache is invalid, or the cache needs to be refreshed, the request must be rescheduled to NetworkDispatcher.
(1). member variables
BlockingQueue <Request <?> MCacheQueue cache Request queue
BlockingQueue <Request <?> MNetworkQueue network Request queue
The Cache mCache Cache class represents a Cache that can obtain the request results and store the request results.
ResponseDelivery mDelivery request result passing class
(2). Processing Flowchart

  • NetworkDispatcher. java

A thread is used to schedule and process requests going through the network. After the service is started, requests are continuously processed from the network Request queue. If the queue is empty, the requests are waiting. After the request is processed, the results are passed to ResponseDelivery for subsequent processing, and determine whether the results need to be cached.
(1). member variables
BlockingQueue <Request <?> MQueue network Request queue
Network mNetwork Network Class, representing a Network that can execute requests
The Cache mCache Cache class represents a Cache that can obtain the request results and store the request results.
ResponseDelivery mDelivery: The request result delivery class. The request result or error can be passed to the caller.

  • Cache. java
The cache interface represents a cache that can obtain the request results and store the request results.
(1). Main Methods:
Public Entry get (String key); obtain the requested cache entity through the key
Public void put (String key, Entry entry); stores the cached object of a request
Public void remove (String key); Removes the specified cache entity
Public void clear (); clear Cache
(2). Internal Entry representing the cache object
Member variables and Methods
Byte [] data returned by the data request (Body entity)
The ETag used for cache freshness verification in the String etagHttp Response Header
Long serverDateHttp Response Header response generation time
Long ttl cache expiration time
Long softTtl Cache Time
Map <String, String> responseHeaders
Boolean isExpired () determines whether the cache has expired. The expired cache cannot be used again.
Boolean refreshNeeded () determines whether the cache is fresh. A fresh cache needs to be sent to the server for freshness detection.

  • DiskBasedCache. java
Inherits the Cache class, which is a Disk-based Cache implementation class.
(1). Main Methods:
Public synchronized void initialize () initialization, scan the cache directory to get all cached data summary information and put it into the memory.
Public synchronized Entry get (String key) obtains data from the cache. Obtain the summary information from the summary information, and then read the cached data file to obtain the content.
Public synchronized void put (String key, Entry entry) stores data in the cache. Check whether the cache is full. If yes, delete some data in the cache and create a new cache file.
Private void pruneIfNeeded (int neededSpace) checks whether bytes of neededSpace can be reallocated. If not, some data in the cache will be deleted.
Public synchronized void clear () clears the cache.

Public synchronized void remove (String key) deletes an element in the cache.
(2). CacheHeader class
CacheHeader is the summary information of the cached file, which is stored in the header of the cached file, similar to the Cache. Entry above.

  • NoCache. java
It inherits the Cache class and does not perform any operations on the Cache implementation class. It can be used as a parameter for building RequestQueue to implement a request queue without caching.
  • Network. java
The network interface that processes network requests.
The only method used to execute a specific request.
public NetworkResponse performRequest(Request<?> request) throws VolleyError;
  • NetworkResponse. java
The returned value of the restore mrequest method in the Network. The Request's parseNetworkResponse (...) The method input parameter is the first level in Volley for internal Response conversion.
It encapsulates StatusCode, Headers, and Body of the network request response.
(1). member variables
Int statusCodeHttp response status code
Byte [] dataBody data
Map <String, String> headers responds to Headers
Boolean notModified indicates whether the response is 304
Long networkTimeMs request time consumption
(2) Volley's internal Response conversion Flowchart


  • BasicNetwork. java
Network implementation, the default Network interface implementation class in Volley. Call HttpStack to process the request and convert the result to the NetworkResponse that is processed by ResponseDelivery.
Mainly implements the following functions:
(1). Use HttpStack to execute network requests.
(2) If the Request contains entity information, such as Etag and Last-Modify, verify the cache freshness and process the 304 (Not Modify) response.
(3) If an error occurs, such as timeout or authentication failure, retry until the operation is successful or an exception is thrown (the retry policy is not met.
  • HttpStack. java
The interface used to process Http requests and return request results. Currently, Volley implements the HurlStack Based on HttpURLConnection and the HttpClientStack Based on Apache HttpClient.
The only method to execute the request
Public HttpResponse initiate mrequest (Request <?> Request, Map <String, String> additionalHeaders)
Throws IOException, AuthFailureError;
The Request is executed. The second parameter indicates that an additional Request Headers is added before the Request is initiated.
  • HttpClientStack. java
Implement the HttpStack interface and use Apache's HttpClient for various request methods.
Basically, the common usage of related classes in the org. apache. http package is not described in detail. However, compared with HttpURLConnection below, we can find that HttpURLConnection APIs are much simpler.
  • HurlStack. java
Implement the HttpStack interface and use Java's HttpURLConnection for various request methods.
  • Response. java
The parsed data is encapsulated for transmission. There are two internal interfaces, Listener and ErrorListener, which indicate the callback upon request failure and successful, respectively.
Response constructor is privatized, and objects are built using static methods with two function names that are easier to understand.
  • ByteArrayPool. java
The recycle pool of byte [] is used for recycling byte [], reducing the memory allocation and recovery. An ArrayList sorted from small to large is used as the cache for byte [], and an ArrayList attribute sorted by time is used to clean up elements when the cache is full.
Public synchronized void returnBuf (byte [] buf)
Reclaim used byte [] and insert byte [] into the cache according to the byte [] length in ascending order.
Public synchronized byte [] getBuf (int len)
Obtain byte [] with a length not less than len, traverse the cache, find the first byte [] with a length greater than the input parameter len, and return the result. If there is no suitable byte [] in the end, new.
Private synchronized void trim ()
When the cached byte exceeds the preset size, delete the earliest byte [] in the FIFO order.
  • PoolingByteArrayOutputStream. java
Inherit ByteArrayOutputStream. The original ByteArrayOutputStream is used to accept the buf written to bytes. When the space is insufficient, a larger byte [] is added. poolingByteArrayOutputStream uses ByteArrayPool as the Byte [] cache to reduce this operation, thus improving performance.
  • HttpHeaderParser. java
The Http header parsing tool class is mainly used in Volley to parse the Header and determine whether the returned result needs to be cached. If you need to return the relevant information in the Header.
There are three methods
public static long parseDateAsEpoch(String dateStr)
Parses the time format of RFC1123 into the epoch time.
public static String parseCharset(Map<String, String> headers)
Resolves the replica set and obtains the replica set in the Content-Type header. If not found, the ISO-8859-1 is returned by default.
public static Cache.Entry parseCacheHeaders(NetworkResponse response)
An important method is to control the Header and Body content through the cache in the network response to build a cache entity. If the Cache-Control field of the Header contains no-cache or no-store, no Cache is returned.
(1). Obtain the response generation time based on the Date header.
(2). Obtain the response OBJECT tag Based on the ETag header.
(3) Calculate the Cache expiration time and Cache freshness time based on the Cache-Control and Expires headers.
Two notes:
1. The Last-Modify header is not processed, but the Date header is stored, and the If-Modified-Since is constructed using Date in subsequent freshness verification. This is against the semantics of Http 1.1.
2. Calculate the expiration time. The Cache-Control header takes precedence over the Expires header.
  • RetryPolicy. java
Retry Policy Interface
There are three methods:
Public int getCurrentTimeout ();
Obtain the current request (for Log)
Public int getCurrentRetryCount ();
Get the number of retries (for Log)
Public void retry (VolleyError error) throws VolleyError;
Determine whether to retry. The parameter is the specific information of this exception. This API is called when a request exception occurs. An input exception can be thrown in this function implementation to stop retry.
  • DefaultRetryPolicy. java
Implements RetryPolicy, which is the default retry policy implementation class of Volley. Mainly through retry (...) Function to determine whether the number of retries has reached the upper limit and whether to continue the Retry.
The mCurrentTimeoutMs variable indicates the number of retries.
MBackoffMultiplier indicates the timeout before each retry.
The mCurrentTimeoutMs variable indicates the timeout Time of the current retry. mBackoffMultiplier is used as the factor to accumulate the timeout of the previous retries.
  • ResponseDelivery. java
The transmission interface of the Request result, which is used to pass the request result or request error.
There are three methods:
public void postResponse(Request<?> request, Response<?> response);
This method is used to pass the request results. The request and response parameters indicate the request information and response result information respectively.
public void postResponse(Request<?> request, Response<?> response, Runnable runnable);
This method is used to pass the request results and run Runnable after the transfer is completed.
public void postError(Request<?> request, VolleyError error);
This method is used to transmit request errors.
  • ExecutorDelivery. java
The specific implementation class of the Request result transmission interface.
If the Request result or Request error generated by the cache scheduling thread or network scheduling thread is transmitted in the corresponding thread of Handler, Request. deliverResponse (…) is called when the Request is successful (...) Function. If the call fails, Request. deliverError (…) is called (...) Function.
  • StringRequest. java
Inherits the Request class, representing a Request whose return value is String. Parses the result data returned by the network to the String type. Passing parameters through listener of the constructor supports onResponse (…) after successful requests (...) Callback.
  • JsonRequest. java
Abstract class, inherited from Request, representing a Request whose body is JSON. Provides methods to construct JSON request parameters.
  • JsonObjectRequest. java
Inherits from JsonRequest and resolves the result data returned by the network to the JSONObject type.
  • JsonArrayRequest. java
Inherits from JsonRequest and resolves the result data returned by the network to the JSONArray type.
  • ImageRequest. java
Inherits the Request class, representing a Request whose return value is Image. Parses the result data returned by the network to the Bitmap type.
You can set the maximum width and height of the image, and calculate the appropriate size to return. A maximum of one image can be parsed at a time to prevent OOM.
  • ImageLoader. java
It encapsulates ImageRequst's easy-to-use image loading tool class.
1. You can set custom ImageCache, which can be a memory cache or a Disk cache to cache the acquired images and reuse them to reduce requests.
2. You can define the image displayed during the image request process and the image displayed after the request fails.
3. Send only one request with the same address and size to avoid repeated requests.
  • NetworkImageView. java
ImageLoader can be used to load the ImageView of network images.
There are three public methods:
public void setDefaultImageResId(int defaultImage)
Set the default image, which is displayed during image loading.
public void setErrorImageResId(int errorImage)
Set an incorrect image. The image cannot be loaded and displayed.
public void setImageUrl(String url, ImageLoader imageLoader)
Set the Url and ImageLoader of the network image. The ImageLoader is used to obtain the network image.
If a new image loading request exists, the old image view loading request is canceled.
  • Abstracherequest. java
Used to manually clear Http cache requests.
After being added to RequestQueue, it can be executed very quickly because the Priority is high and it is Priority. IMMEDIATE. The cache clearing method mCache. clear () is written in the isCanceled () method body, which can be executed as early as possible.
Mongoacherequest is not written in the same way. At present, it seems that the only advantage is that it can also be used as a request to clear the cache. The clearing operation in isCanceled () causes ambiguity. No one knows the source code. In the NetworkDispatcherrun method loop process, isCanceled () this read operation may result in the cache being cleared. It can only be used as an Hack operation as explained in the source code.
  • Authenticator. java
Identity Authentication interface, used for basic authentication or digest authentication. This class is an interface Volley uses to connect with authentication, such as OAuth. However, it is not widely used and Volley's internal combination is not very close.
  • AndroidAuthenticator. java
Inherits Authenticator and implements authentication Interaction Based on Android AccountManager.
  • VolleyLog. java
Volley's Log tool class.
  • VolleyError. java
The parent class of all error exceptions in Volley inherited from Exception. You can use this class to set and obtain the NetworkResponse or request time.
  • AuthFailureError. java
Inherited from VolleyError, which indicates an error occurred during request authentication, such as 401 and 403 of RespondeCode.
  • NetworkError. java
Inherited from VolleyError, indicating a network error.
  • ParseError. java
Inherited from VolleyError, indicating a content parsing error.
  • ServerError. java
Inherited from VolleyError, indicating a server error.
  • TimeoutError. java
Inherited from VolleyError, indicating a request timeout error.
  • NoConnectionError. java

It is inherited from NetworkError, indicating that a connection cannot be established.

10. https://github.com/wintonBy/android-volley-manager.git


/*

QQ group: 372702757

*/


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.