Implementation and comparison of AsyncTask and Handler asynchronous Methods

Source: Internet
Author: User

Implementation and comparison of AsyncTask and Handler asynchronous Methods

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, the interface is provided to feedback the degree of asynchronous execution (UI progress update can be implemented through the interface), and the execution result is finally 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 Handler asynchronous implementation principles and advantages and disadvantages

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

The AsyncTask class is easy to use, that is, to implement several methods. The onPreExecute () method is some initialization operations that are executed at the beginning of the task, such as a progress bar at the beginning, then, execute the doInBackground () method, which mainly involves business operations, such as database queries. onProgressUpdate () is called when this method is executed. You can update the UI interface in this method, finally, the onPostExecute () method is called. After the business result is obtained, the method can be returned to the UI thread, or some resources opened when the business is executed can be closed. We can see that the AsyncTask class is a generic class. The three parameters of this class correspond to doInBackground (String... params), onProgressUpdate (String... values), The onPostExecute (String result) parameter, is very good. If you do not need to pass the parameter and return value, you can use Void instead. DoInBackground (String... the Return Value of the params method is the parameter value of the onPostExecute (String result) method, because the value returned after the doInBackground method is executed is processed in onPostExecute (String result.

When handler is used for processing, You Need To Know several handler-related components, logoff and Queue. In fact, logoff is used to put the messages sent by handler into the Queue, and broadcast the message to all the handler related to this Queue, while the Queue is usually allocated to this thread when the main thread is enabled, therefore, to communicate with the UI main thread, you must use the handler object associated with this Queue. Generally, the handler object created in that thread is associated with the queue of that thread, therefore, the handler object created in the UI thread communicates with the UI thread, so that we can send messages to the main thread in the Child thread to update the UI. Then how does the main thread handle the message consumption sent by the subthread? In fact, when generating a handler object, we need to implement the handleMessage () method of the handler object. This method is the method that the main thread accepts and processes the messages sent by the Child thread, to update the UI thread.

Many netizens may find that many apps on the Android platform use AsyncTask instead of Thread and Handler to update the UI. What are the differences between them, which solution should we use at ordinary times. The system has introduced AsyncTask to Android since android 1.5. in the OS package, in the past, when the 1.1 and 1.0 sdks officially named it UserTask, it was a newly added concurrent library starting with JDK 1.5, users who have worked on J2EE may understand the efficiency and power of the concurrent library, which is more flexible and powerful than the original Java Thread, but the lightweight usage is more occupied by system resources. Thread was designed to implement multithreading in Java in the early days. It is relatively simple and does not support many features of concurrent which need to be implemented by themselves in synchronization and Thread pool classes, for distributed applications, you need to write scheduling code by yourself. For the refreshing of Android UI, Google introduces the Handler and logoff mechanisms, which are implemented based on messages, sometimes the Message Queue may be blocked or cannot be used accurately for other reasons.

We recommend that you use AsyncTask instead of Thread + Handler, Which is simpler to call and more reliable to be tested, google uses a large number of asynchronous tasks in Browser as time-consuming I/O operations, such as downloading files and reading and writing databases. They are essentially inseparable from messages, however, AsyncTask is more reliable and easier to maintain than Thread-based Handler. However, AsyncTask has some disadvantages. For example, once the Thread is enabled, the dobackground method cannot send messages to the Thread, the logic can only be controlled through pre-configured tags. Of course, the logic can be communicated by changing the pending flag bit of the Thread. For some applications, Thread, Handler, and logoff may be more flexible.

This article describes how to use AsyncTask and Handler.

First, we need to clarify the next concept, what is a UI thread. As the name implies, the ui thread is the one that manages the user interface!

Android ui thread operations are not secure, and operations that directly interact with the user interface must be performed in the ui thread. This mode is called the single thread mode.

In single-thread mode, make sure that you do not block the ui thread and access the ui component only in the ui thread.

When we want to execute a complex and time-consuming algorithm and finally reflect the computing result to the ui, we will find that we cannot guarantee the above two requirements at the same time; we will surely think of opening a new thread to let this complicated and time-consuming task be executed in the background, but the execution is complete? We found that we could not interact with the ui.

To solve this problem, android provides us with many solutions.

1) handler and message mechanisms: interaction with the ui through display throws and Capture messages;

2) Activity. runOnUiThread (Runnable): if the current thread is a ui thread, it will be executed immediately; otherwise, the thread operations in the parameter will be placed in the event queue of the ui thread, waiting for execution.

3) View. post (Runnable): puts the operation into the message queue. If the operation is put successfully, it will be executed in the ui thread and return true; otherwise, false is returned.

4) View. postDelayed (Runnable, long) is basically the same as the third, but a delay time is added.

5) android1.5 provides a tool class for us to solve this problem.

AsyncTask is an abstract class. It 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.

What developers need to do when using program calls is to implement these methods.

1) subclass AsyncTask

2) implement one or more of the following methods defined in AsyncTask

OnPreExecute (), this method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface.

DoInBackground (Params ...), It will be executed immediately after the onPreExecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishProgress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.

OnProgressUpdate (Progress ...), After the publishProgress method is called, the UI thread calls this method to display the progress of the task on the interface, for example, through a progress bar.

OnPostExecute (Result). After doInBackground is executed, the onPostExecute method will be called by the UI thread, and the background computing Result will be passed to the UI thread through this method.

To correctly use the AsyncTask class, the following guidelines must be followed:

1) The Task instance must be created in the UI thread.

2) The execute method must be called in the UI thread.

3) do not manually call onPreExecute (), onPostExecute (Result), doInBackground (Params ...), OnProgressUpdate (Progress ...) These methods

4) The task can only be executed once. Otherwise, exceptions may occur during multiple calls.

Java language:

Packagecn.com. chenzheng_java;

Importandroid. OS. AsyncTask;
/**
*
* @ Author chenzheng_java
* @ Description asynchronous task AcyncTask example
*
*/
PublicclassMyAsyncTaskextendsAsyncTask {

/**
* This method is called by the ui thread, where you can access the ui components.
* In many cases, we will display a progress bar here to show that the background is
* Execute a function.
*/
@ Override
ProtectedvoidonPreExecute (){
Super. onPreExecute ();
}

/**
* This method is called by the background process to perform calculations that are time-consuming.
* This method is called after the onPreExecute method. Of course
* The publishProgress method can be called every several seconds to update
* Progress information
*/
@ Override
ProtectedObjectdoInBackground (String... params ){
Returnnull;
}

/**
* After publishProgress is called in doInBackground, the ui thread will
* Call this method. You can dynamically change the progress of the progress bar here to let users know
* Current progress.
*/
@ Override
ProtectedvoidonProgressUpdate (Integer... values ){
Super. onProgressUpdate (values );
}

/**
* After doInBackground is executed, it is called by the ui thread. Here you can
* Return the final result of our calculation to the user.
*/
@ Override
ProtectedvoidonPostExecute (Objectresult ){
Super. onPostExecute (result );
}
}

The following describes the most essential multithreading: hanlder and message mechanisms:

Why multithreading is required:

In daily applications, we usually need to perform operations that are "invisible to Users" in the background. For example, we need to download a music, if your application can perform other operations only after the user downloads the application, it will definitely make the user very uncomfortable. At this time, we usually do this by letting these operations go to the background for execution. Then, after the background execution is complete, the user will be prompted accordingly. At this time, we need to use the multithreading mechanism, and then execute these operations by creating a new thread.

Now that we understand the requirements, we are ready to implement them. However, after further understanding, we found that the thread mechanism in android is that it can only interact with users in the UI thread. When we create a new thread and execute some background operations, after the execution is complete, we want to pop up a dialog box for the user to confirm, but the tragic discovery, we cannot return the main UI thread at all.

(Description: What is a UI thread: the UI thread is the thread of the interaction interface you see currently ).

To implement these functions, we need a handler and message mechanism provided by android.

Let's first explain the programming mechanism:

We usually create a handler in the UI thread, which is equivalent to a processor. It is mainly responsible for processing and binding the message to the handler thread. Each handler must be associated with a logoff, and the two correspond one by one. Note that this is very important! In addition, logoff is responsible for extracting messages from its internal messageQueue to handler for processing. Because handler is implemented in the UI thread, after such a handler and message mechanism, we can return to the UI thread.

Handler: A staff member who processes the data returned by background processes.

What is message: the data returned by the background process, which can store data formats such as bundle

MessageQueue: it is a part of the logoff corresponding to the thread. It stores the message bound to the current handler that is thrown back from the background process and is a queue.

What is looper: loageis equivalent to a messageQueue administrator. It will traverse the queue continuously, and then take out qualified messages one by one to handler for processing.

Note that handler is declared in the UI thread. If we directly execute a thread using similar code, we do not actually create a new thread, because handler has been bound to logoff in the default UI thread.

If you are interested, you can check the default null constructor of Handler to find the cause. The logoff of the current UI thread is directly bound to it.

The following is a simple and practical example.

Java language: packagecn.com. src;

Importcn.com. chenzheng_java.utils.R;
Importandroid. app. Activity;
Importandroid. OS. Bundle;
Importandroid. OS. Handler;
Importandroid. OS. HandlerThread;
Importandroid. OS. logoff;
Importandroid. OS. Message;
Importandroid. util. Log;
Importandroid. view. View;
Importandroid. view. View. OnClickListener;
Importandroid. widget. Button;

/**
* @ Author chenzheng_java
* Handler and message Test Cases
*/
PublicclassHanlderMessageTestextendsActivityimplementsOnClickListener {
Buttonbutton;
MyHandlerhandler;

@ Override
ProtectedvoidonCreate (BundlesavedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button = (Button) this. findViewById (R. id. button1 );
Button. setOnClickListener (this );

}

// Declare your handler
PrivateclassMyHandlerextendsHandler {
/**
* Using the default constructor, handler is bound to the Logoff of the current UI thread.
* If you want to use multithreading, the default constructor cannot be used here.
*/
PublicMyHandler (){
Super ();
}

PublicMyHandler (looperloler ){
Super (logoff );
}

// Process the specific message, which is inherited by the parent class.
@ Override
PublicvoidhandleMessage (Messagemsg ){
IntwhatNumber = msg. what;
Bundlebundle = (Bundle) msg. obj;
Log. I ("what", whatNumber + "");
Log. I ("name", bundle. getString ("name "));
Log. I ("gender", bundle. getString ("sex "));
Log. I ("age", bundle. getString ("age "));
Super. handleMessage (msg );
}
}

// For custom tasks, Runnable is usually implemented.
PrivateclassMyThreadimplementsRunnable {
/**
* This method implements specific tasks, such as downloading.
* The Message contains data that you want to interact with the ui thread. In principle
* It is best not to directly call handler.
**/
@ Override
Publicvoidrun (){

Try {
Thread. sleep (6000 );
Messagemessage = Message. obtain (handler );
Message. what = 10;
Bundlebundle = newBundle ();
Bundle. putString ("name", "chenzheng ");
Bundle. putString ("sex", "genius ");
Bundle. putString ("age", "unknown year of birth and death ");
Message. obj = bundle;
Log. I ("notification", "message started ");
Log. I ("Notification thread_id:", "" + Thread. currentThread (). getId ());
Message. sendToTarget ();
} Catch (effectione ){
Log. I ("notification", "An error occurred while thread sleep! ");
E. printStackTrace ();
}
}
}

@ Override
PublicvoidonClick (Viewv ){
Log. I ("Notification thread_id:", "" + Thread. currentThread (). getId ());

// Create a thread containing logoff. If HandlerThread is not called, The MyThread behind the thread is directly put into the UI thread queue.
HandlerThreadmyHandlerThread = newHandlerThread ("chenzheng_java ");
// Start a new thread
MyHandlerThread. start ();
// Bind the handler to a new thread
Handler = newMyHandler (myHandlerThread. getLooper ());
// Execute the task in the new thread
Handler. post (newMyThread ());
}
}

Related Article

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.