Android Asynctask Asynchronous task

Source: Internet
Author: User

First, Asynctask: (i), Related knowledge Review: 1, the development of Android applications must comply withSingle Thread ModelPrinciple: Android UI actions are not thread-safe, and they must be executed in the UI thread.
2, the single-threaded model always have to remember the two rules:
1). Do not block the UI thread;
2). Make sure that the Android UI controls are accessible only in the UI thread.
When a program starts for the first time, Android initiates a correspondingMain Thread(Main Thread), the main thread is primarily responsible for handling UI-related events, such as user keystroke events, User touch screen events, and screen drawing events, and distributing related events to the corresponding components for processing. So the main thread is often calledUI Thread。
3, Android4.0 or above version,access to the network is not allowed in the main thread。 Programs that involve network operations are generally required to open a new thread to complete network access. However, after you have obtained the page data, you cannot return the data to the UI interface. BecauseChild Threads(Worker Thread) cannot directly access members in the UI thread, that is,There is no way to manipulate the content on the UI interfaceIf the operation, an exception is thrown: Calledfromwrongthreadexception.
In fact, Android provides several ways to access the UI thread in other threads:
    • Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable, long)
    • Handler messaging mechanism (explained in subsequent courses)
These classes or methods make the code complex and difficult to understand. To solve this problem, Android 1.5 provides a tool class: Asynctask, which makes it easier to create tasks that run interactively with the user interface for long periods of time. Asynctask is more lightweight and works with simple asynchronous processing without the need for threading and handler.

(b), Asynctask code implementation:
1. Asynctask is an abstract class. Asynctask defines three generic type params,progress and result.
    • The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request. Generally with String type;
    • Progress the percentage of background task execution. General use of Integer type;
    • Result the results of the final return of the task in the background, usually with byte[] or String.

2, the implementation of Asynctask is divided intoFour Steps, each step corresponds to a callback method (the method that is called automatically by the application), and the developers need to implement these methods.
1) Define the subclass of the Asynctask; 2) Implement the methods defined in Asynctask: (can be fully implemented or only partially implemented)
    • OnPreExecute (), the method is called by the UI thread before performing the actual background operation. You can do some preparatory work in this method, such as displaying a progress bar on the interface.
    • Doinbackground (Params ...), which executes immediately after the OnPreExecute method executes, runs in the background thread. This will be primarily responsible for performing time-consuming background computations. You can call the Publishprogress method to update the real-time task progress. The method is an abstract method that the subclass must implement.
    • Onprogressupdate (Progress ...), after the Publishprogress method is called, the UI thread will invoke this method to show the progress of the task on the interface, for example, by displaying it through a progress bar.
    • OnPostExecute (Result), after Doinbackground execution completes, the OnPostExecute method is called by the UI thread, and the results of the background are passed through the method to the UI thread.



3. Core code:
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (                Savedinstancestate);                Setcontentview (R.layout.activity_main);                Text_main_info = (TextView) Findviewbyid (r.id.text_main_info); New Myasynctask (Mainactivity.this). execute         (urlstring); }
Class Myasynctask extends Asynctask<string, Integer, byte[]> {private context context;                Private ProgressDialog pdialog = null;                        Public Myasynctask (Context context) {This.context = context; Instantiate a ProgressDialog progress dialog box Pdialog =New ProgressDialog(context); Pdialog.SetIcon(R.drawable.ic_launcher); Pdialog.Settitle("Progress tip:"); Pdialog.Setmessage("Data Load ..."); The following method sets the style for the progress box, if the parameter is 1 or progressdialog.style_horizontal represents the exact progress bar pdialog.Setprogressstyle(Progressdialog.style_horizontal);                        Note: when new ProgressDialog () is set to the second parameter, the above statement is not required.                If the second parameter is 0, which indicates the Blur progress bar, if 1 is the precise progress bar, it is necessary to calculate the progress value.                        } @Override protected void OnPreExecute () {super.onpreexecute (); Pdialog.Show();//Make Progress dialog box display} @Override protected void Onprogressupdate (Integer ... values) {                        Super.onprogressupdate (values); Keep the values on the progress dialog box constantly changing.                        The values of the parameters are the data that is returned from the Doinbackground () method continuously. Pdialog.setprogress  (Values[0]); } @Override protected byte[] Doinbackground (String ... params) {Buffe                        Redinputstream bis = null;                        Bytearrayoutputstream BAOs = null;                        HttpURLConnection httpconn = null;                                Access the network and download the data start try {URL url = new URL (params[0]);                                Httpconn = (httpurlconnection) url.openconnection ();                                Httpconn.setrequestmethod ("GET");                                Httpconn.setconnecttimeout (8000);                                Httpconn.setdoinput (TRUE);                                Httpconn.connect (); if (httpconn.getresponsecode () = =) {bis = new Bufferedinputstream (httpconn.get                                        InputStream ());            BAOs = new Bytearrayoutputstream ();                            This length here stands for the whole file of the lengths int length = Httpconn.getconten                                        Tlength ();                                        This variable represents the length of the data that has been read int readlength = 0;                                        byte[] buffer = new BYTE[256];                                        int c = 0; while ((c = bis.read (buffer))! =-1) {//Readlength + = C, in order to calculate the total that has been read until the current                                                Length readlength + = C;                                                Writes bytes into the memory stream, which in the future can be conveniently mounted as a byte array baos.write (buffer, 0, C);                                                Baos.flush (); Here is the calculation of the download progress.                                                Use the length that has been read divided by the total length of the file.                int progress = (int) (Readlength/(float) length * 100);                                Keep your progress posted to make it easy for the Onprogressupdate () method to continually revise the data in the progress dialog box after receiving itpublishprogress  (progress);                                } return Baos.tobytearray ();//Returns the contents of the memory stream to a byte array.                        }} catch (Exception e) {e.printstacktrace ();                                        Finally {//the necessary streams and connections are closed to release the resource try {                                        Bis.close ();                                        Baos.close ();                                Httpconn.disconnect ();                                } catch (Exception e) {e.printstacktrace ();                }} return null; } @Override protected void OnPostExecute (byte[] result) {Super.onpos                        Texecute (result);                              if (result! = null) {  Displays the downloaded content in the specified text box text_main_info.settext (result); } else {//If the download is empty, prompt for download failure. If you do not make a judgment, it is easy to get a null pointer exception Text_main_info.settext ("Download failed!                        "); }//Let the progress dialog box disappear Pdialog.Dismiss(); }        }

4, in order to correctly use the Asynctask class, here are a few guidelines that must be followed: 1) The instance of the task must be created in the UI thread, 2) The Execute method must be called in the UI thread, 3) do not manually call OnPreExecute (), O Npostexecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These methods; 4) The task can only be executed once, otherwise the exception will occur when multiple calls are made; the Doinbackground method and the OnPostExecute parameter must correspond, both of which are specified in the Asynctask declaration's generic parameter list, and the first is a doinb Ackground accepts the parameter, the second is the parameter that shows the progress, the third is the Doinbackground return and onpostexecute the passed in parameter.

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.