Android: AsyncTask application for asynchronous processing (2), androidasynctask

Source: Internet
Author: User

Android: AsyncTask application for asynchronous processing (2), androidasynctask

Preface

In the previous article Android: Handler + Thread application of asynchronous processing (1), we know that the main UI thread of Android is mainly responsible for handling users' button events, users' touch screen events, and Screen Drawing events. Since the old UI is so busy, we developers must be confused about how to block the UI thread or something. Otherwise, in case the UI interface stops responding, isn't it a scolding rhythm ?! Therefore, we know that Handler + Thread is used to process time-consuming tasks in sub-threads. After the task is completed, Handler notifies the UI main Thread to update the UI interface.

However, some people think that the code using Handler + Thread is complicated. Of course, some of them include our great Google. Therefore, AsyncTask (asynchronous task) is born in Android 1.5. Compared with Handler, AsyncTask is more lightweight and suitable for simple asynchronous processing due to better encapsulation. Of course, it is also relatively simple to use, it's really Google's son!

Overview

AsyncTask is an abstract class that is generally inherited. AsyncTask maintains a static Thread pool, and each background task is submitted to the Thread pool for running. It also uses the Handler + Thread mechanism to call various callback methods of AsyncTask; the callback method runs in the main thread, so we understand what to do (~ O ~)~ ZZ (hurry up with the UI ).

We know that AsyncTask <Params, Progress, Result> is an abstract class. here we can see that it supports three types of generics:

1. Params: when our AsyncTask is about to start working, the type of the parameter we input to him, that is, the parameter passed to the backend.

2. Progress: The parameter type of AsyncTask to report its working Progress to us. For example, it is the percentage of the download Progress.

3. Result: The background execution task is completed. The parameter type of the returned Result is

If we do not need to specify a generic type, we can specify the Void by the authorizer. AsyncTask will not be sad.

Of course, Google also helps us to run the following five statuses of AsyncTask background tasks:1. Prepare for running; 2. running in the background; 3. Updating progress; 4. Completing background tasks; 5. Canceling tasks. Each status has a corresponding callback method in AsyncTask.

1. Prepare for running: OnPreExecute (). This callback method is called in the UI thread immediately when the task is enabled, and is also called before the time-consuming operations in the background are executed. This method is usually used to complete initialization, for example, display the progress bar on the interface.

2. running in the background: DoInBackground (Params ...), this callback function is called immediately after the onPreExecute () method is executed by the background thread. rewriting this method is a time-consuming task to be completed by the background thread, therefore, we cannot update the UI directly here. We should use publishProgress (Progress ...) trigger callback method onProgressUpdate (Progress ...) progress update. The task calculation result must be returned by this function and passed to onPostExecute.

3. Progress Update:OnProgressUpdate (Progress ...), calling the publishProgress () method in doInBackground () to update the task execution progress will trigger this method in the main thread, which is generally used to dynamically display a progress bar.

4. Complete background tasks:OnPostExecute (Result). After doInBackground () is completed, the system automatically calls the onPostExecute () method and passes the return value of doInBackground () to this method.

5. Cancel the task:OnCancelled (), called when the cancel () method of AsyncTask is called.

Case

Reference code:

Public class MainActivity extends ActionBarActivity implements OnClickListener {private Button startdownload; private ProgressBar probar; private TextView TV; private downask task; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); startdownload = (Button) findViewById (R. id. startdownload); probar = (ProgressBar) FindViewById (R. id. probar); TV = (TextView) findViewById (R. id. TV); startdownload. setOnClickListener (this) ;}@ Override public void onClick (View v) {task = new downask (); // execute of the same AsyncTask can only call task.exe cute ("input parameter, can be empty "); // after you call execute, the onPreExecute method will be called back.} class downask extends AsyncTask <String, Integer, String >{@ Override // This method is not run in the main thread, time-consuming operations can be performed, and the UI interface cannot be updated. Other Methods run protected String doInBackground (String... params) {// params is the input parameter for execute (int I = 1; I <= 100; I ++) {try {// simulate the download operation Thread. sleep (333); publishProgress (I); // pass the parameter I and trigger the onProgressUpdate callback method} catch (InterruptedException e) {e. printStackTrace () ;}} String result = "task completed"; return result; // call onPostExecute and pass the result to the callback method} @ Override protected void onPreExecute () {// After the callback method is executed, the doInBackground probar will be called. setMax (100); probar. setProgre Ss (0); TV. setText ("START download") ;}@ Override protected void onPostExecute (String result) {// call back this method after the doInBackground ends and ends. Toast. makeText (MainActivity. this, result, Toast. LENGTH_SHORT ). show (); TV. setText ("download completed") ;}@ Override protected void onProgressUpdate (Integer... values) {// notify the UI to update probar. setProgress (values [0]) ;}}

Layout file:

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <Button android: id = "@ + id/startdownload" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Start download"/> <ProgressBar android: id = "@ + id/probar" android: layout_width = "match_parent" android: layout_height = "wrap_content" style = "@ android: style/Widget. progressBar. horizontal "/> <TextView android: id =" @ + id/TV "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: textColor = "#000000" android: textSize = "20sp"/> </LinearLayout>

Code Description:

1. click the Button to instantiate an inherited sub-class of AsyncTask. A task is created. Next, execute the execute (params) method to start the asynchronous task. (An instance of the same AsyncTask can only execute once, and an error will be thrown if it is executed multiple times ).

2. After execute () is executed, the onPreExecute () callback method is triggered to set the initial attribute of the progress bar. After onPreExecute () is executed, doInBackground (params) will be executed in the background thread. This method receives the parameters passed in by execute for time-consuming operations. This is a simulated Network File Download task.

3. doInBackground () is running in the background thread. to interact with the UI main thread to update the progress, you can call the publishProgress (values) method, this will trigger the callback method of onProgressUpdate (values) running in the main UI thread. The progress of the progress bar will be updated here in the code.

4. After the background task is executed, call onPostExecute (Result). The input parameter is the object returned by doInBackground.

Notes

1. Do not execute () multiple times in the same AsyncTask instance. The correct method is to execute () once in a new AsyncTask instance ().

2. Time-consuming tasks must be processed in doInBackground (). Do not process time-consuming tasks in other callback methods to avoid blocking of the main UI thread.

3. Do not update the UI in doInBackground (). Use publishProgress () to call the callback method to update the UI.

4. onCancelled () can only trigger the cancel () method of AsyncTask and cannot cancel the thread Tasks running in the thread pool. However, you can use the flag to stop the thread tasks.

5. In different android versions, AsyncTask runs in multiple tasks. Some tasks can be executed in parallel or in sequence. However, in Android versions, you can set the thread pool execution rules by specifying parameters.

6. AsyncTask is suitable for processing short-time operations and long-time operations. For example, to download a large video, you need to use your own thread to download it, whether it is breakpoint download or other.

 

 

By enjoy wind chimes
Source:Http://www.cnblogs.com/net168/
The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and provide a connection to the original article clearly on the article page. Otherwise, you will not be reposted next time.

 


Android development cainiao uses asynchronous AsyncTask for network download. mMyAsynvTaskexecute (mUrl) is not executed.

AsyncTask has different execution policies in different SDK versions,
Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence by default.
That is, Android 3.0 and AsyncTask are sequential execution methods.
As a result, AsyncTask is not executed because other AsyncTask tasks have not been executed yet.
Solution:
1. Use Thread + handler or runonuithread.
2. Use
You can tell Android to run it in parallel with the usage of the executeOnExecutor () method, specifyingAsyncTask. THREAD_POOL_EXECUTOR as first parameter.
For example:
MyAsynvTask.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR );

Which of the following threads calls the android AsyncTask method?

This is simple and generally involves three methods,
1. onPreExecute (),
Called before high-Load Code Execution, usually used to display a progress bar and execute it in the main thread

2. doInBackGround ():
OnPreExecute () is called after execution. This method usually puts high load code, such as remote requests and massive data loading. You do not need to create a new thread to wrap this method AsyncTask (or subclass) this method is automatically called in the new thread.

3. onPostExecute (Result ),
Call after doInBackground is complete. Generally, it sets the result and cancels the progress bar displayed in the first method.

OnProgressUpdate () is generally used to update the progress bar displayed in the first method. What download 50% 51%...

In short, subclass AsyncTask. You don't have to worry about the thread issue. In the main thread, you can directly subclass the new AsyncTask and call execute. You must call execute in the main thread. Also, these are the life cycle methods of AsyncTask. Do not call them by yourself.

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.