In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today Xiaobian to share with you about the Android framework of Volley source code analysis of the relevant knowledge, detailed content, clear logic, I believe that most people are too aware of this knowledge, so share this article for your reference, I hope you will learn something after reading this article, let's take a look at it.
Volley is easy to use
I am here in the form of a dependency package, and you can also rely on it in the form of gradle.
All right, let's go to the code.
/ / get the request object of volley RequestQueue requestQueue = Volley.newRequestQueue (getApplicationContext ()); StringRequest stringRequest = new StringRequest (StringRequest.Method.GET, "http://www.baidu.com", new Response.Listener () {@ Override public void onResponse (String s) {Log.d (" MainActivity ","-> "+ s) }, new Response.ErrorListener () {@ Override public void onErrorResponse (VolleyError volleyError) {Log.d ("MainActivity", "--volleyError-- >" + volleyError);}}); requestQueue.add (stringRequest)
As you can see from the code, first newRequestQueue to get a request queue, and then add the StringRequest request to the request queue, it's as simple as that. Of course, the request is not worth StringRequest, as well as JsonObjectRequest, ImageRequest, etc., but the usage is the same, so there is no code here. The simple use of Volley makes it possible to make requests. Isn't it simple?
Principle of Volley implementation
Take a picture first.
Let's take a look at how newRequestQueue is executed internally. At first, the code executes several overloaded methods in succession, and finally goes to newRequestQueue.
Public static RequestQueue newRequestQueue (Context context, HttpStack stack, int maxDiskCacheBytes) {File cacheDir = new File (context.getCacheDir (), "volley"); String userAgent = "volley/0"; try {String packageName = context.getPackageName (); PackageInfo info = context.getPackageManager (). GetPackageInfo (packageName, 0); userAgent = packageName + "/" + info.versionCode;} catch (NameNotFoundException var7) { } / / A verdict is made here that HTTPClient,2.3 was used before 2.3.After HTTPClient,2.3, HttpURLConnection if (stack = = null) {if (VERSION.SDK_INT > = 9) {stack = new HurlStack ();} else {stack = new HttpClientStack (AndroidHttpClient.newInstance (userAgent));}} Network network = new BasicNetwork ((HttpStack) stack); RequestQueue queue If (maxDiskCacheBytes request = (Request) this.mCacheQueue.take (); / / get a request request.addMarker ("cache-queue-take") from the cache queue If (request.isCanceled ()) {/ / determines whether the request is cancelled, and if it is cancelled, then finish the request to request.finish ("cache-discard-canceled") } else {Entry entry = this.mCache.get (request.getCacheKey ()) If (entry = = null) {/ / if the content fetched from the cache is empty, add the request to the network thread and request request.addMarker again ("cache-miss"); this.mNetworkQueue.put (request) } else if (entry.isExpired ()) {/ / if the request expires, add the request to the network thread and request request.addMarker ("cache-hit-expired") again; request.setCacheEntry (entry) This.mNetworkQueue.put (request);} else {/ / callback data to the main thread request.addMarker ("cache-hit") Response response = request.parseNetworkResponse (new NetworkResponse (entry.data, entry.responseHeaders)); request.addMarker ("cache-hit-parsed") If (entry.refreshNeeded ()) {request.addMarker ("cache-hit-refresh-needed"); request.setCacheEntry (entry); response.intermediate = true This.mDelivery.postResponse (request, response New Runnable () {public void run () {try {CacheDispatcher.this.mNetworkQueue.put (request) } catch (InterruptedException var2) { }) } else {this.mDelivery.postResponse (request, response) }} catch (InterruptedException var4) {if (this.mQuit) {return }}}
There are several loops nested here, which is a bit messy, but if you analyze it slowly, you will find that it is actually very clear. I wrote it on the note, so I won't repeat it here.
Let's take a look at NetworkDispatcher and see how network threads execute. Also find the run () method
Public void run () {Process.setThreadPriority (10); while (true) {long startTimeMs; Request request; while (true) {startTimeMs = SystemClock.elapsedRealtime (); try {request = (Request) this.mQueue.take (); / / get a request break } catch (InterruptedException var6) {if (this.mQuit) {return;} try {request.addMarker ("network-queue-take") If (request.isCanceled ()) {/ / if the request is cancelled, the request finish will be dropped request.finish ("network-discard-cancelled");} else {/ / make a network request this.addTrafficStatsTag (request); NetworkResponse networkResponse = this.mNetwork.performRequest (request) Request.addMarker ("network-http-complete"); if (networkResponse.notModified & & request.hasHadResponseDelivered ()) {request.finish ("not-modified");} else {Response response = request.parseNetworkResponse (networkResponse); request.addMarker ("network-parse-complete") If (request.shouldCache () & & response.cacheEntry! = null) {this.mCache.put (request.getCacheKey (), response.cacheEntry); request.addMarker ("network-cache-written");} request.markDelivered () This.mDelivery.postResponse (request, response);} catch (VolleyError var7) {var7.setNetworkTimeMs (SystemClock.elapsedRealtime ()-startTimeMs); this.parseAndDeliverNetworkError (request, var7) } catch (Exception var8) {VolleyLog.e (var8, "Unhandled exception% s", new Object [] {var8.toString ()}); VolleyError volleyError = new VolleyError (var8); volleyError.setNetworkTimeMs (SystemClock.elapsedRealtime ()-startTimeMs); this.mDelivery.postError (request, volleyError);}
There is a lot of code, so we go directly to NetworkResponse networkResponse = this.mNetwork.performRequest (request); this code, this code is the code that requests the network, the core. PerformRequest is an interface. Let's take a look at the performRequest () method. When Network begins to say version judgment, there is a code Network network = new BasicNetwork ((HttpStack) stack). From this code, we can know that BasicNetwork is the class that finally implements the network request, and we find the performRequest method.
Public NetworkResponse performRequest (Request request) throws VolleyError {long requestStart = SystemClock.elapsedRealtime (); while (true) {HttpResponse httpResponse = null; byte [] responseContents = null; Map responseHeaders = Collections.emptyMap (); try {Map headers = new HashMap (); this.addCacheHeaders (headers, request.getCacheEntry ()) HttpResponse = this.mHttpStack.performRequest (request, headers); StatusLine statusLine = httpResponse.getStatusLine (); int statusCode = statusLine.getStatusCode (); responseHeaders = convertHeaders (httpResponse.getAllHeaders ()); if (statusCode = 304) {Entry entry = request.getCacheEntry () If (entry = = null) {return new NetworkResponse (304, (byte []) null, responseHeaders, true, SystemClock.elapsedRealtime ()-requestStart);} entry.responseHeaders.putAll (responseHeaders); return new NetworkResponse (304, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime ()-requestStart) } if (statusCode = = 301 | | statusCode = = 302) {String newUrl = (String) responseHeaders.get ("Location"); request.setRedirectUrl (newUrl);} byte [] responseContents If (httpResponse.getEntity ()! = null) {responseContents = this.entityToBytes (httpResponse.getEntity ());} else {responseContents = new byte [0];} long requestLifetime = SystemClock.elapsedRealtime ()-requestStart; this.logSlowRequests (requestLifetime, request, responseContents, statusLine) If (statusCode > = 200 & & statusCode = 9) {stack = new HurlStack ();} else {stack = new HttpClientStack (AndroidHttpClient.newInstance (userAgent));}} above is all the content of the article "Volley Source Code Analysis of Android Framework". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.