Use AsyncTask to implement multithreading and asynctask to implement Multithreading

Source: Internet
Author: User

Use AsyncTask to implement multithreading and asynctask to implement Multithreading

Preface

In Android Application Development, we sometimes need to synchronize tasks. The AsyncTask class in Android can help us better manage Thread synchronization (asynchronous mode), just like what the Thread class can do, but its usage is simpler than that of Thread.


This blog includes the following two parts:

1. Introduction to AsyncTask

2. Instance


I. Introduction to AsyncTask


When you develop an Android Application, if a time-consuming task (usually a subthread) exists in an Activity and the task calls/operates the main thread, the Application will throw the famous "ANR" (Application Not Responding) error.


Figure 1: ANR


The AsyncTask class can help us solve the problem. Using AsyncTask allows us to use the main thread correctly and easily, even if another asynchronous thread is created at this time. It enables time-consuming tasks to be executed in the background and displays the execution results in the foreground (UI Thread or main Thread) without the need for Thread or Handler classes. Inter-thread communication becomes simpler and more elegant.


* The main Thread (User Interface Thread UI Thread) is the Thread responsible for interaction with the User Interface in Android.


AsyncTask is an abstract class that must be inherited before it can be instantiated. There are three generic parameters:Params,SSAndResult:


-Params: The parameter passed to the executed task, that isDoInBackgroundMethod parameters.


-SS: During the execution of background tasks, the parameters passed in when updating are displayed in the main thread, that isOnProgressUpdateMethod parameters.


-Result: The result returned by the background task, that isOnPostExecuteMethod parameters.


In addition, when inheriting the AsyncTask class, four methods are generally required. Of course, applications do not need to call these methods. These methods will be automatically called During task execution: onPreExecute, doInBackground, onProgressUpdate, and onPostExecute (the doInBackground abstract method must be overwritten):


-OnPreExecute: This method is executed in the main thread to initialize the task.


-DoInBackground: This method is executed in the background. This method is available inOnPreExecuteAfter the method is executed, start. The operations executed in this method can be time-consuming and will not block the main thread. By callingPublishProgressMethod to display the result update of background tasks in the main thread.


-OnProgressUpdate: This method is also executed in the main thread.PublishProgressWhen the method is called, this method is executed.DoInBackgroundCan be called only during execution.


-OnPostExecute: InDoInBackgroundThe method that starts after the method is executed. This method is called only after the background task is completed, and is also executed in the main thread.


Ii. Instances

To better display the use of AsyncTask, we can implement a small timer application. First, create an Android project named "AsyncTaskActivity" (the name does not matter). Modify the xml file in res-> layout that defines the main user interface:


Main. xml


<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:padding="15dp" >                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:padding="5dp"        android:text="Time in min"        android:textSize="18dp"        android:textStyle="bold" />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          <EditText        android:id="@+id/chronoValue"        android:layout_width="100dp"        android:layout_height="wrap_content"        android:gravity="center"        android:layout_marginBottom="15dp"        android:layout_gravity="center"        android:hint="minutes"        android:inputType="number"        android:singleLine="true"        android:text="1"        android:textSize="15dp" />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          <TextView        android:id="@+id/chronoText"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:gravity="center"        android:text="0:0"        android:textSize="80dp" />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          <Button        android:id="@+id/start"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="15dp"        android:text="Start" />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      </LinearLayout>


In the preceding main. in the xml file, we mainly define an EditText for entering the time to be counted, A TextView for displaying the changes in the count, and a Button for starting the Count task.


In our class AsyncTaskActivity, we first declare three private variables, corresponding to the above three elements.


private Button start;private TextView chronoText;private EditText chronoValue;


Create an internal class that inherits the AsyncTask class and is named "Chronograph", which is a stopwatch or timer.


private class Chronograph extends AsyncTask<Integer, Integer, Void> {    @Override    protected void onPreExecute() {        super.onPreExecute();        // Disable the button and edittext before the start of the deduction        chronoValue.setEnabled(false);        start.setEnabled(false);        chronoText.setText("0:0");    }    @Override    protected Void doInBackground(Integer... params) {        // Deduction        for (int i = 0; i <= params[0]; i++) {            for (int j = 0; j < 60; j++) {                try {                    // Publication of increment                    publishProgress(i, j);                    if (i == params[0]) {                            return null;                    }                    // Pause for one second                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }        if (isCancelled()) {            return null;        }        return null;    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         @Override    protected void onProgressUpdate(Integer... values) {        super.onProgressUpdate(values);        // Update on the User Interface        chronoText.setText(values[0] + ":" + values[1]);    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         @Override     protected void onPostExecute(Void result) {        super.onPostExecute(result);        // Reactivation of the button and edittext        chronoValue.setEnabled(true);        start.setEnabled(true);    }}


Above, we have rewritten the four methods we need. Finally, we will complete the onCreate method of the AsyncTaskActivity class:

@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);                                                                                                                                                                                                                                                                                                                                                                                                                                                                   // Recuperation of the usable components    start = (Button)findViewById(R.id.start);    chronoText = (TextView)findViewById(R.id.chronoText);    chronoValue = (EditText)findViewById(R.id.chronoValue);                                                                                                                                                                                                                                                                                                                                                                                                                                                                   start.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {            // Recuperation of the value in the EditText            int value = Integer.parseInt(String.valueOf(chronoValue.getText()));            // Verification of the content            if (value > 0) {                new Chronograph().execute(value);            }            else {        Toast.makeText(AsyncTaskActivity.this, "Please enter a correct value !", Toast.LENGTH_LONG).show();            }        }    });}


If we do not need any of the three parameters when inheriting the AsyncTask class, we can define it as the Void type (Note: it is different from the lower-case void type). For example:


private class Chronograph extends AsyncTask<Integer, Integer, Void> {...}


Run our project to get the results shown in the following three figures:



Figure 2: Before pressing the Start button






Figure 3: Counting




Figure 4: After counting



Summary

In the future, when an asynchronous task needs to be executed, you can use the AsyncTask class, which can be customized as needed.


AsyncTask uses the Thread Pool mechanism, making it possible to execute multiple AsyncTask at the same time. However, it should be noted that the thread pool capacity is five threads to execute at the same time. If the number of threads exceeds this limit, the redundant threads must wait until the threads in the thread pool are executed to start.


Therefore, when using AsyncTask, it is better to clearly know that the task will end with a definite and reasonable conclusion. Otherwise, it is better to use the traditional Thread class.


Appendix: source code of the Instance Project


Baidu cloud disk download link: http://pan.baidu.com/s/1sj36O5v



When AsyncTask is used to implement an asynchronous thread, an exception occurs during the second call. How can this problem be solved? For details about the exception, see the description.

Handler must be written in the main thread, and cannot be used as a thread action in Handler. handler. sendMessage should be used in the sub-thread to avoid confusion.
 
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.

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.