Android-AsyncTask and Handler

Source: Internet
Author: User

Android-AsyncTask and Handler

 

Comparison between AsyncTask and Handler

1) AsyncTask implementation principle, and applicable advantages and disadvantages

AsyncTask is a lightweight asynchronous class provided by android. It can inherit AsyncTask directly and implement asynchronous operations in the class,AndProvide interface feedback to the currentAsynchronous execution degree(UI progress update can be implemented through the interface), and finally the execution result is fed back to the main UI thread.

Advantages:

L simple and fast

L process controllable

Disadvantages:

L it becomes complicated when multiple asynchronous operations and Ui changes are required.

2) principle and advantages and disadvantages of Handler asynchronous implementation

When Handler is implemented asynchronously, it involves four objects: Handler, logoff, Message, and Thread. the asynchronous process is that the main Thread starts thread (subthread) à Thread (subthread) run and generate Message-à logoff to get the Message and pass it to Handler. the Handler gets the Message in logoff one by one and changes the UI.

Advantages:

L clear structure and clear Function Definition

L simple and clear for multiple background tasks

Disadvantages:

L in asynchronous processing of a single backend, there are too many codes and the structure is too complex (relative)

Introduction to AsyncTaskAndroid AsyncTask is more lightweight than Handler and is suitable for simple asynchronous processing. First, it is clear that Android has Handler and AsyncTask to avoid blocking the main thread (UI thread), and UI Updates can only be completed in the main thread, so asynchronous processing is inevitable.

Android provides AsyncTask to reduce the development difficulty. AsyncTask is a encapsulated background task class. as its name implies, it is an asynchronous task.

AsyncTask directly inherits from the Object class and is located in android. OS. AsyncTask. To use AsyncTask, we need to provide three generic parameters and reload several methods (at least one ).

AsyncTask defines three generic types: Params, SS, and Result.

Input parameters for Params startup task execution, such as the URL of the HTTP request. Percentage of Progress background tasks. Result: The Result returned when the task is executed in the background, such as String.

All the students who have used AsyncTask know that the following two methods are required to load data asynchronously:

DoInBackground (Params ...) The operations in the background can be put here. Note that you cannot directly operate the UI here. This method is executed in the background thread to complete the main work of the task, usually takes a long time. You can call publicProgress (Progress…) during execution ...) To update the task progress. OnPostExecute (Result) is equivalent to Handler's way of processing the UI, where you can use the Result processing operation UI obtained in doInBackground. This method is executed in the main thread. The task execution result is returned as a parameter of this method.

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

OnProgressUpdate (Progress ...) You can use the progress bar to increase user experience. This method is executed in the main thread to display the task execution progress. OnPreExecute () is the interface used by the end user to call Excute. This method is called before the task is executed. The progress dialog box is displayed here. OnCancelled () the operation to be performed when the call is canceled

When using the AsyncTask class, the following guidelines must be followed:

The Task instance 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 methods; the task can only be executed once; otherwise, exceptions may occur during multiple calls;

An example of a simple understanding of AsyncTask:

Main. xml

 

? Xml version = 1.0 encoding = UTF-8?>
       
       
   
    
   
  
 
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 button;          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 ProgressBarAsyncTask(textView, progressBar);                      asyncTask.execute(1000);                  }              });          }      }  

 

NetOperator. java

 

Package vic. wong. main;/*** simulate the network environment * @ author liuyazhuang */public class NetOperator {public void operator () {try {// sleep Thread for 1 second. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block 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. * The first is the onProExecute method. * The second is the doInBackgroup Method * @ author liuyazhuang */public class ProgressBarAsyncTask extends AsyncTask.
 
  
{Private TextView textView; private ProgressBar progressBar; public ProgressBarAsyncTask (TextView textView, ProgressBar progressBar) {super (); this. textView = textView; this. progressBar = progressBar;}/*** the Integer parameter here corresponds to the first parameter in AsyncTask * the String return value corresponds to the third parameter in AsyncTask * this method is not running in the UI thread, it is mainly used for asynchronous operations, all spaces in the UI cannot be set or modified in this method * But the publishProgress method can be called to trigger onProgressUpdate to operate the UI */@ Override protected String doInBackground (Integer... params) {NetOperator netOperator = new NetOperator (); int I = 0; for (I = 10; I <= 100; I ++ = 10) {netOperator. operator (); publishProgress (I);} return I + params [0]. intValue () +;}/*** here, the String parameter corresponds to the third parameter in AsyncTask (that is, receiving the doInBackground return value) * after the doInBackground method is executed, you can also set the UI space when running in the UI thread */@ Override protected void onPostExecute (String result) {textView. setText (Asynchronous Operation execution ends + result);} // This method runs in the UI thread and can be set in the UI thread to @ Override protected void onPreExecute () {textView. setText (start asynchronous thread execution);}/*** the Intege parameter here corresponds to the second parameter in AsyncTask * in the doInBackground method ,, every time publishProgress method is called, onProgressUpdate will be triggered to execute * onProgressUpdate is executed in the UI thread, and all operations can be performed on the UI space */@ Override protected void onProgressUpdate (Integer... values) {int vlaue = values [0]; progressBar. setProgress (vlaue );}}
 

 

 

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.