Asynchronous network requests in Android

Source: Internet
Author: User

In this article, let's write a basic Android asynchronous network request framework to learn about the posture of network requests in Android. Due to the limited personal level, there is inevitably negligence and falsehood, I hope you can point out, thank you all:

1. Synchronizing Network requests

Take the GET request for HTTP as an example, let's introduce the implementation of a basic synchronization request framework in Android. Direct Sticker Code:

 Public classHttputils { Public Static byte[] Get (String urlstring) {httpurlconnection URLConnection=NULL; Try{URL URL=NewURL (urlstring); URLConnection=(HttpURLConnection) url.openconnection (); //Set Request MethodUrlconnection.setrequestmethod ("GET"); //setting the time-out periodUrlconnection.setconnecttimeout (5000); Urlconnection.setreadtimeout (3000); //Get the status code of the response            intResponsecode =Urlconnection.getresponsecode (); if(Responsecode = = 200) {Bytearrayoutputstream BOS=NewBytearrayoutputstream (); InputStream in=Urlconnection.getinputstream (); byte[] buffer =New byte[4 * 1024]; intLen =-1;  while(len = in.read (buffer))! =-1) {bos.write (buffer,0, Len);                } close (in); byte[] result =Bos.tobytearray ();                Close (BOS); returnresult; } Else {                return NULL; }        } Catch(Exception e) {e.printstacktrace (); } finally {            if(URLConnection! =NULL) {urlconnection.disconnect (); }        }        return NULL; }    Private Static voidClose (closeable stream) {if(Stream! =NULL) {            Try{stream.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}

Believe that the above code we are not unfamiliar, the above code to achieve the basic synchronous network request function, the Get method will return a byte[] array, subsequent we can based on the corresponding type returned (text or picture) This byte array for further processing.

2. Asynchronous Network requests

Typically an asynchronous HTTP GET request is this: when a call to a GET method is issued, the related task is automatically executed in the background thread, and we continue to work on the other in the main thread, and when it successfully obtains the response to the GET request, it will callback the Onsuccess method. The most straightforward notation usually looks like this:

 Public classAsynchttputils { Public Static byte[] Get (String URL, ResponseHandler handler) {FinalHandler Mhandler =NewHandler (); NewThread (NewRunnable () {@Override Public voidrun () {Final byte[] result =httputils.get (URL); Handler.post (NewRunnable () {@Override Public voidrun () {responsehandler.onsuccess (result);
}
});
}
});
}
}

Where the ResponseHandler interface is defined as follows:

 Public Interface ResponseHandler {    void  onsucess (bytep[] result);

As we can see, the code for implementing an asynchronous get request is straightforward, but there is a problem: a thread is created each time a request is made, so a large number of large threads are created when the request is more frequent, so the overhead of creating, destroying, and threading the thread is significant. And the thread object is an anonymous inner class object that implicitly holds the perimeter class reference and may cause memory Leak.

For these problems, we can use the thread pool to avoid unnecessary cost of creating and destroying threads, and the following code for the Asynchttputils class is improved:

 Public classAsynchttputils {//gets the number of CPUs for the current device     Public Static Final intCpu_count =runtime.getruntime (). Availableprocessors (); //The core pool size is set to the number of CPUs plus 1    Private Static Final intCore_pool_size = Cpu_count + 1; //set the maximum size of the thread pool    Private Static Final intMax_pool_size = 2 * cpu_count + 1; //Survival Time    Private Static Final LongKeep_alive = 5L; //To create a thread pool object     Public Static FinalExecutor Threadpoolexecutor =NewThreadpoolexecutor (core_pool_size, Max_pool_size, Keep_alive, Timeunit.seconds,NewLinkedblockingqueue<runnable>());  Public Static voidGetFinalString URL,FinalResponseHandler ResponseHandler) {        FinalHandler Mhandler =NewHandler (Looper.getmainlooper ()); //Create a new request taskRunnable requestrunnable =NewRunnable () {@Override Public voidrun () {Final byte[] result =httputils.get (URL); if(Result! =NULL) {Mhandler.post (NewRunnable () {@Override Public voidrun () {//result NOT NULL indicates successful request, callback Onsuccess methodresponsehandler.onsuccess (Result);                }                    });        }            }        };    Threadpoolexecutor.execute (requestrunnable); }}

The above code is mainly to use the thread pool to achieve the purpose of threading reuse, about the thread pool more in-depth introduction, you can see here: in-depth understanding of Java thread Pool

3. References

Android Docs

Asynchronous network requests in Android

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.