Step by Step _android Development Course [7]_asynctask Study

Source: Internet
Author: User
Tags message queue

Focus on technology, enjoy life! --qq:804212028
Browse Links: http://blog.csdn.net/y18334702058/article/details/44624305

    • Topic: Asynctask Learning

      -When developing an Android mobile client, you often use multithreading to do it, and we often put time-consuming operations on separate threads to avoid taking the main thread and creating a bad user experience for the user. However, the main thread (UI thread) cannot be manipulated in a child thread, and an error occurs when manipulating the UI thread in a child thread. So Android provides a class handler to update the UI thread in a child thread, updating the UI interface with a message-sending mechanism and presenting it to the user. This solves the problem of the child thread updating the UI. However, time-consuming task operations always start some anonymous sub-threads, and too many sub-threads bring a huge burden on the system, resulting in some performance problems. So Android provides a tool class Asynctask, which, as the name implies, executes tasks asynchronously. This asynctask is born to handle some of the more time-consuming tasks behind the scenes, to give users a good user experience, from the programming syntax is much more elegant, no longer need child threads and handler to complete the asynchronous operation and refresh the user interface.

Advantages of Asynctask:

1, the cost of the thread is large, if each task to create a thread, then the efficiency of the application is much lower;
2, the thread can not be managed, the anonymous thread is created and started without the control of the program, if there are many requests sent, then will start a very large number of threads, the system will be overwhelmed.
3. In addition, as seen earlier, updating the UI in a new thread also has to introduce handler, which makes the code look bloated.

Asynctask defines three types of generics

They are params,progress and result respectively.
1. The Params starts the input parameters of the task execution, such as the URL of the HTTP request.
2. Progress the percentage of background task execution.
3. Result the results of the final return of the task in the background, such as String.

Asynctask a few points to pay attention to the place

Is the problem 1:asynctask multithreaded?

Answer: Yes.

Question 2:asynctask who is more lightweight than handler?

A: By looking at the source code, found that Asynctask is actually a thread pool, and the online saying is asynctask than handler to lightweight, obviously inaccurate, can only say, Asynctask in code than handler to lightweight, And actually more resource-intensive than handler, because Asynctask is a thread pool! And handler just sent a message queue, the connection is not open.
However, if the data for an asynchronous task is particularly large, the benefits of Asynctask this thread pool structure are reflected.

Asynctask Replace handler to change the main thread UI display

ImportAndroid. RImportandroid.app.Activity;ImportAndroid.app.ProgressDialog;ImportAndroid.content.Context;ImportAndroid.content.DialogInterface;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public  class asynctest extends Activity {    PrivateTextView message;PrivateButton Open;PrivateEditText URL;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (r.layout.network);        Message = (TextView) Findviewbyid (r.id.message);        url = (EditText) Findviewbyid (R.id.url);        Open = (Button) Findviewbyid (R.id.open); Open.setonclicklistener (NewView.onclicklistener () { Public void OnClick(View arg0)            {Connect ();    }        }); }Private void Connect() {Pagetask task =NewPagetask ( This); Task.execute (Url.gettext (). toString ());The parameter number of this function is variable, can pass 0, 1, 2 or more,                                                //When calling this function the system will automatically call the Doinbackgound () function.} class Pagetask extends Asynctask<string, Integer, string> {//These three parameters correspond to Excute (String),        //Onprogressupdate (Integer), Onpostresult (string) The parameter types inside the three methods        //variable-length input parameters, corresponding to Asynctask.exucute ()ProgressDialog Pdialog; Public Pagetask(Context context) {Pdialog =NewProgressDialog (Context,0); Pdialog.setbutton ("Cancel",NewDialoginterface.onclicklistener () { Public void OnClick(Dialoginterface Dialog,inti) {dialog.cancel ();            }            }); Pdialog.setoncancellistener (NewDialoginterface.oncancellistener () { Public void OnCancel(Dialoginterface Dialog)                {Finish ();            }            }); Pdialog.setcancelable (true); Pdialog.setmax ( -);            Pdialog.setprogressstyle (progressdialog.style_horizontal);        Pdialog.show (); }@Override        protectedStringDoinbackground(String ... params) {//used to accept parameters inside the Excute (String)            Try{inti =0; while(I <= -) {publishprogress (i++);//The number of parameters of this function can also be changedThread.Sleep ( +); }            }Catch(Exception e)            {E.printstacktrace (); }return "Download Complete"; }@Override        protected void oncancelled() {Super. oncancelled (); }@Override        protected void OnPostExecute(String result) {//This parameter is to accept the return value of Doinbackgound ()            //Returns the contents of the HTML pageMessage.settext (result);//Pdialog.dismiss ();}@Override        protected void OnPreExecute() {//Task start, you can display a dialog box here, simple to handleMessage.settext ("Start Download"); }@Override        protected void onprogressupdate(Integer ... values) {//This parameter is the parameter that accepts publishprogress (Integer)            //Update ProgressSystem.out.println (""+ values[0]); Message.settext (""+ values[0]); Pdialog.setprogress (values[0]); }    }}

Focus on technology, enjoy life! --qq:804212028
Browse Links: http://blog.csdn.net/y18334702058/article/details/44624305

Step by Step _android Development Course [7]_asynctask Study

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.