Asynchronous explanation of Android Development (2)-AsyncTask

Source: Internet
Author: User

Asynchronous explanation of Android Development (2)-AsyncTask

 

I once introduced how to implement asynchronous operations through Thread + Handler in Thread + Handler of asynchronous explanation of Android Development (I. For more information, see.

Although Thread + Handler can update the UI of the main Thread and implement Asynchronization, the Thread + Handler mode needs to create a new Thread for each task, after the task is completed, the Handler instance sends a message to the UI thread to update the interface. This method provides fine control over the entire process, but also has some disadvantages, such as tedious code, when multiple tasks are executed simultaneously, it is difficult to precisely control the threads.

The following describes how to use AsyncTask in Android:

 

AsyncTask introduction:

The system has introduced AsyncTask to the Android. OS package since android 1.5. 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.

 

Class Overview:

The emergence of AsyncTask makes the use of UI threads lightweight and simple. This class allows you to perform background operations and update the operation results to the UI thread without having to operate threads and handlers.

AsyncTask is designed around the thread and Handler, and does not constitute a general thread framework. It is best to use short jobs for asynchronous tasks. If you need to keep the thread running for a long time, you can use the ThreadPoolExecutor and FutureTask APIs provided by java. util. concurrent package to replace it.

An asynchronous task is defined as an operation that runs on the background thread and the UI thread to publish the result. Asynchronous task is definedParams,SSAndResult3 common types, andOnPreExecute,DoInBackground,OnProgressUpdateAndOnPostExecuteStep 4.

 

AsyncTask Definition

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

Public abstract classAsyncTask

Input parameters for Params startup task execution, such as the URL of the HTTP request.

Progress of the background task execution in Progress.

Result: The Result returned when the task is executed in the background, such as String.

 

The main methods in AsyncTask are described as follows:

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 or instantiating some controls. This method does not need to be implemented.

DoInBackground (Params...) will be executed immediately after the onPreExecute method is executed. This method runs in the background thread. Here, we will be mainly responsible for performing the time-consuming background processing. 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 ...), in publishProgress (Progress ...) after a 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 is called by the UI thread. The background computing Result is passed to the UI thread through this method and displayed on the interface to the user.

OnCancelled (), called when the user cancels the thread operation. It is called when onCancelled () is called in the main thread.

 

Steps for using AsyncTask

AsyncTask allows you to perform asynchronous operations on your user interface. It executes time-consuming operations in a child Thread, and then publishes execution results on the UI Thread, without the need to process the Thread and Handler.

To use AsyncTask, you must inherit AsyncTask and implement the doInBackground () callback method. AsyncTask runs in a background thread pool. To update your UI, you should implement the onPostExecute () method,It gets results from the doInBackground () method and runs in the UI thread, so that you can safely update your UI.You can call the execute () method in the UI thread to start your task.

 

Steps for using AsyncTask:

1) create a class that inherits AsyncTask

2) Implement the abstract method doInBackground (Params...) defined in AsyncTask, and then rewrite other methods as needed.

3) execute () is called to start the task.

Let's look at an example:

 

//
 
  
// Parameters sent from the call location // Integer: the progress of reading network data // class NetTask extends AsyncTask returned from the network
  
   
{Private String path; private ImageView iv; public NetTask (String path, ImageView iv) {this. path = path; this. iv = iv;} // in the main thread, feedback the network access progress @ Override protected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); Log. I (NetUtil, values = + values [0]);} // in the main thread, run @ Override protected void onPreExecute () {super. onPreExecute ();} // sub-thread @ Override protected Bitmap doInBackg Round (String... params) {try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set some connection attributes conn. setConnectTimeout (5000); conn. setRequestMethod (GET); // POST // sets the http header information // conn. setRequestProperty (Content-type, newValue) if (conn. getResponseCode () == 200) {InputStream is = conn. getInputStream (); return BitmapFactory. decodeStream (is) ;}} catch (Malforme DURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return null;} // when the network returns data in the main thread, run @ Override protected void onPostExecute (Bitmap result) {super. onPostExecute (result); if (result! = Null) {iv. setImageBitmap (result );}}}
  
 

 

Note:

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

1) The AsyncTask 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 ...) the AsyncTask needs to be instantiated in the UI thread to call these methods.

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

5) The doInBackground method and the onPostExecute parameter must match,These two parameters are specified in the generic parameter list declared by AsyncTask. The first parameter is the one accepted by doInBackground, and the second parameter is the parameter indicating the progress, the third parameter is the doInBackground return and the parameter passed in onPostExecute.

 

Advantages and disadvantages of Thread + Handler mode and AsyncTask:

AsyncTask implementation principles and 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:

1) simple and fast

2) process controllable

Disadvantages:

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

 

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 the Thread (subthread) run and generate Message-Logoff to get the Message and pass it to HandlerHandler to get the Message in logoff one by one, and change the UI.

Advantages:

1) clear structure and clear Function Definition

2) It is simple and clear for multiple background tasks

Disadvantages:

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

Finally, it should be noted that AsyncTask cannot completely replace threads. In some logic that is complicated or needs to be repeatedly executed in the background, Thread + Handler may be required to implement it.

If you think this blog post is helpful to you, please give it a compliment! You can also follow fengyuzhengfan's blog to learn more! Http://blog.csdn.net/fengyuzhengfan/

 

 

 

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.