Android--asynctask and handler control

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/46952835

Asynctask and handler control

1) Asynctask implementation of the principle, and the advantages and disadvantages of the application

Asynctask, the lightweight asynchronous class provided by Android, is able to inherit Asynctask directly, implement asynchronous operations in the class, and provide interface feedback about the current level of asynchronous Operation (which enables UI progress updates through an interface). The result of the last feedback run is given to the UI main thread.

Advantages of Use:

L Simple, fast

L Process controllable

Disadvantages of using :

L becomes complex when multiple asynchronous operations are used and UI changes are required.

2) The principle of handler asynchronous implementation and the advantages and disadvantages of its application

When Handler is implemented asynchronously, it involves Handler, Looper, Message,thread four objects, the process of implementing asynchronous is the main thread starting thread (child thread) àthread (child thread) Executes and generates Message-àlooper gets a message and passes it to Handleràhandler to get the message in Looper one by one and make UI changes.

Advantages of Use:

L structure clear, function definition clear

L for multiple background tasks. Simple. Clear

Disadvantages of using:

L appear to be too much code in a single background asynchronous process. The structure is too complex (relativity)

Asynctask IntroductionAndroid's Asynctask is a little more lightweight than handler. Applies to simple asynchronous processing. First understand that Android has handler and Asynctask, all in order not to block the main thread (UI thread), and UI updates can only be completed in the main thread, so asynchronous processing is unavoidable.

Android has provided asynctask to reduce the difficulty of this development. Asynctask is a packaged background task class, as its name implies, an asynchronous task.


Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we're going to provide three generic parameters and reload several methods (at least one).

Asynctask defines three types of generic type params,progress and result.

    • The input parameters for the Params startup task to run, such as the URL of the HTTP request.
    • Progress the percentage of background task runs.
    • The result of the results background run task is finally returned. For example, String.

Students who have used Asynctask know that a minimum number of asynchronous load data to override the following two methods:

    • Doinbackground (Params ...) runs in the background, and the time-consuming operation can be put here. Note that it is not possible to manipulate the UI directly. This method runs on a background thread, and it usually takes a long time to complete the task's main work. Ability to invoke publicprogress (Progress ...) during operation To update the progress of the task.

    • OnPostExecute (Result) is equivalent to the way handler handles the UI, where it can use the results that are obtained in the Doinbackground processing operation UI. This method runs on the main thread. The result of the task run is returned as a parameter to this method

If necessary, you have to rewrite the following three methods, but they are not required:

    • Onprogressupdate (Progress ...) Ability to use the progress bar to add user experience. This method runs on the main thread and is used to show the progress of the task running.
    • OnPreExecute () Here is the interface at last when the user calls Excute. This method is called before the task starts. The ability to display the Run Progress dialog box here.
    • Oncancelled () The action to be made when the user calls Cancel

Use the Asynctask class. Here are a few guidelines to follow:

    • The instance of the task must be created in the UI thread;
    • The Execute method must be called in the UI thread.
    • Do not manually call OnPreExecute (), OnPostExecute (Result). Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;
    • The task can only be run once, otherwise the exception will occur when multiple calls are made;

An ultra-simple example of understanding Asynctask:

Main.xml

? xml version= "1.0" encoding= "Utf-8"?

> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= " Vertical " android:layout_width=" fill_parent " android:layout_height=" fill_parent " > < TextView android:id= "@+id/textview01" android:layout_width= "fill_parent" android:layout_height= " Wrap_content " /> <progressbar android:id=" @+id/progressbar02 " android:layout_width=" Fill_parent " android:layout_height=" wrap_content " style="? Android:attr/progressbarstylehorizontal " /> <button android:id= "@+id/button03" android:layout_width= "Fill_parent " android:layout_height= "Wrap_content" android:text= "update ProgressBar" /> </LinearLayout>

Mainactivity.java

    Package vic.wong.main;      Import android.app.Activity;      Import Android.os.Bundle;      Import Android.view.View;      Import Android.view.View.OnClickListener;      Import Android.widget.Button;      Import Android.widget.ProgressBar;      Import Android.widget.TextView; /**  * @author Liuyazhuang  */public class Mainactivity extends Activity {private Button B          Utton;          Private ProgressBar ProgressBar;                    Private TextView TextView;              @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                            Setcontentview (R.layout.main);              Button = (button) Findviewbyid (R.ID.BUTTON03);              ProgressBar = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR02);                            TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW01);                               Button.setonclicklistener (New Onclicklistener () {     @Override public void OnClick (View v) {progressbarasynctask asynctask = new Pr                      Ogressbarasynctask (TextView, ProgressBar);                  Asynctask.execute (1000);          }              });   }      }

Netoperator.java

    Package vic.wong.main;            /**     * Simulated network environment     * @author Liuyazhuang     *     /public class Netoperator {public                    void operator () {              try { c10/>//sleeps 1 seconds                  Thread.Sleep (+),              } catch (Interruptedexception e) {                  //TODO auto-generated catch block< C14/>e.printstacktrace ();}}}              
Progressbarasynctask. java
    Package vic.wong.main;      Import Android.os.AsyncTask;      Import Android.widget.ProgressBar;            Import Android.widget.TextView;     /** * Generate the object of this class and call the Execute method after * First run is the Onproexecute method * Second Run Doinbackgroup method * @author Liuyazhuang */public class Progressbarasynctask extends Asynctask<integer, Integer, string> {private Tex          TView TextView;                              Private ProgressBar ProgressBar;              Public Progressbarasynctask (TextView TextView, ProgressBar ProgressBar) {super ();              This.textview = TextView;          This.progressbar = ProgressBar;           }/** * Here the integer parameter corresponds to the first parameter in the Asynctask * Here the string return value corresponding to the third parameter of the Asynctask * The method does not run in the UI thread. Used primarily for asynchronous operations, where the space in the UI cannot be set and changed in this method * but can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI */@Over   Ride protected String doinbackground (Integer ... params) {           Netoperator netoperator = new Netoperator ();              int i = 0;                  for (i = ten; I <=; i+=10) {netoperator.operator ();              Publishprogress (i);          } return i + params[0].intvalue () + ""; }/** * The string parameter here corresponds to the third parameter in the Asynctask (that is, the return value of the receiving Doinbackground) * in the Doinbackground side              Run at the end of the method run, and run in the UI thread where the UI space can be set */@Override protected void OnPostExecute (String result) {          Textview.settext ("Asynchronous Operation run End" + result);              }//The method runs in the UI thread and runs in the UI thread where it is able to set the UI space @Override protected void OnPreExecute () {          Textview.settext ("Start running asynchronous Threads"); }/** * Here Intege the second parameter in the corresponding Asynctask * in the Doinbackground method. , each call to the Publishprogress method triggers the onprogressupdate run * onprogressupdate is run in the UI thread, all of which can manipulate the UI space */@Ov Erride Protected void Onprogressupdate (Integer ... values) {int vlaue = values[0];          Progressbar.setprogress (Vlaue);   }                    }

Android--asynctask and handler control

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.