Introduction to this section:

This section brings you a lightweight class provided by Android for handling asynchronous tasks: AsyncTask. We generally inherit AsyncTask, then implement asynchronous operations in the class, and then feed back the progress of asynchronous execution to the UI main thread~ Well, some concepts may be unclear to everyone, and I think it is necessary to explain the concept of multithreading. So let's first explain some conceptual things!


1. Related Concepts

1) What is multithreading:

Answer: First, you need to understand these terms: application, process, thread, multithreading!!

  • Application: A set of instructions (a set of static code) written in some language to accomplish a specific task.
  • Process :A running program, a unit for system scheduling and resource allocationindependent unit, the operating system allocates a section of memory space for each process; a program's dynamic execution goes through the complete process of code loading -> execution -> completion!
  • Thread: A smaller execution unit than a process. Each process may have multiple threads.A thread needs to be placed in a process to execute!Threads are managed by the program!!! Processes are scheduled by the system!!!
  • Multithreading concept: Execute multiple instructions in parallel, dividing the CPU'stime slicesaccording to the scheduling algorithm, allocate them to each thread. In fact, it istime-sharing execution, but the switching time is very short, so users just feel it is simultaneous!

A simple example:You are logged into QQ, and suddenly want to listen to music. Do you need to close QQ and then start some XX player? The answer is no. We can directly open the player to play music while QQ is still running, right! This is simple multithreading. In actual development, there are also such examples. For instance, when an application is running and a new version is found, and you want to update in the background, at this time we usually create a background thread to download the new version of the APK, but we can still use other functions in the application! This is an example of using multithreading~

2) Concepts of synchronous and asynchronous:

Answer:Synchronous: When we execute a function, before getting the result, the call cannot return! Simply put, you must wait for the previous thing to finish before doing the next thing. For a simple example: if you are having sex, in order to avoid causing a pregnancy, you must first put on a condom, and then have sex, right? Condom on -> then have sex. If you don't have a condom, then the sex operation has to wait until you buy a condom and put it on, and only then can you start having sex. A vivid example, ♪(^∇^*)Asynchronous: It is the opposite of synchronous. After we execute a function, we do not need to get the result immediately. We can normally do other operations. This function can notify or call back to tell us after completion. Still using the background download example above: with background download, after we execute the download function, we don't need to care about its download process; when the download is complete, it just notifies us~

3) Why does Android introduce asynchronous tasks?

Answer: Because when an Android program starts, it simultaneously starts a corresponding main thread (Main Thread). This main thread is mainly responsible for handling UI-related events! Sometimes we also call it the UI thread! When developing Android apps, we must abide by the rules of this single-thread model:Android UI operations are not thread-safe, and these operations need to be executed in the UI thread!If we are in a non-UI thread, for example, creating another thread with new Thread() from the main thread, and then directly modifying the values of UI controls inside it, the following exception will be thrown:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its viewsIn addition, another point: if we put all time-consuming operations in the UI thread, and if the UI thread does not respond to user requests for more than 5 seconds, then an ANR (Application Not Responding) exception will be triggered, that is, the application is unresponsive. Finally, another point: after Android 4.0, network operations are prohibited in the UI thread; otherwise it will report:android.os.NetworkOnMainThreadException

All the above reasons illustrate the significance of Android introducing asynchronous tasks. Of course, implementing asynchrony does not necessarily require the AsyncTask explained in this section. We can create a thread ourselves, and after completing related operations, update the UI through the following two methods:

  1. The Handler we learned earlier: we write the UI update in the Handler, and then notify the UI to update through methods such as sendMessage(). Also, don't forget the difference between writing Handler in the main thread and in a child thread~
  2. Use Activity.runOnUiThread(Runnable) to put the UI update code in a Runnable. When updating the UI, just pass in the Runnable object~

2. Full Analysis of AsyncTask:


1) Why use AsyncTask?

Answer: We can use the above two methods to complete our asynchronous operations. If the asynchronous operations we need to write are numerous or cumbersome, should we still create a new Thread() and then use the above methods to notify the UI to update? Programmers generally like to be lazy. Since the official has provided us with AsyncTask, a well-packaged lightweight asynchronous class, why not use it? We can complete our asynchronous operations with dozens of lines of code, and the progress can be controlled. Compared with Handler, AsyncTask is simpler and faster. Of course, this is only suitable for simple asynchronous operations. In addition, the most common places where asynchrony is used in practice are network operations, image loading, data transmission, etc. AsyncTask can temporarily meet the needs of beginners and for writing small applications. But when you go to a company and actually work on projects, we more often use third-party frameworks, such as Volley, OkHttp, android-async-http, XUtils, and many others. In the later advanced tutorials, we will choose 1-2 frameworks to learn. Of course, you can find materials to learn by yourself, but it is still necessary to master AsyncTask!


2) Basic structure of AsyncTask:

AsyncTask is an abstract class. Generally, we define a class to inherit AsyncTask and override related methods. Official API:AsyncTask

  • Parameters for constructing an AsyncTask subclass:

  • Related methods and execution flow:

  • Precautions:


3. AsyncTask usage examples:

Because we haven't learned the Android networking part yet, and to take care of beginners, here we use a delayed thread to simulate the file download process. Later when we get to networking, I will write a few more examples for you~

Implementation effect preview:

Layout file: activity.xml:

<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"  
    tools:context=".MyActivity">  
    <TextView  
        android:id="@+id/txttitle"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content" />  
    <!--设置一个进度条,并且设置为水平方向-->  
    <ProgressBar  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/pgbar"  
        style="?android:attr/progressBarStyleHorizontal"/>  
    <Button  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:id="@+id/btnupdate"  
        android:text="更新progressBar"/>  
</LinearLayout> 

Define a delayed operation to simulate the download:

public class DelayOperator {  
    //延时操作,用来模拟下载  
    public void delay()  
    {  
        try {  
            Thread.sleep(1000);  
        }catch (InterruptedException e){  
            e.printStackTrace();;  
        }  
    }  
}

Custom AsyncTask:

public class MyAsyncTask extends AsyncTask<Integer,Integer,String>  
{  
    private TextView txt;  
    private ProgressBar pgbar;  
  
    public MyAsyncTask(TextView txt,ProgressBar pgbar)  
    {  
        super();  
        this.txt = txt;  
        this.pgbar = pgbar;  
    }  
  
  
    //该方法不运行在UI线程中,主要用于异步操作,通过调用publishProgress()方法  
    //触发onProgressUpdate对UI进行操作  
    @Override  
    protected String doInBackground(Integer... params) {  
        DelayOperator dop = new DelayOperator();  
        int i = 0;  
        for (i = 10;i <= 100;i+=10)  
        {  
            dop.delay();  
            publishProgress(i);  
        }  
        return  i + params[0].intValue() + "";  
    }  
  
    //该方法运行在UI线程中,可对UI控件进行设置  
    @Override  
    protected void onPreExecute() {  
        txt.setText("开始执行异步线程~");  
    }  
  
  
    //在doBackground方法中,每次调用publishProgress方法都会触发该方法  
    //运行在UI线程中,可对UI控件进行操作  
  
  
    @Override  
    protected void onProgressUpdate(Integer... values) {  
        int value = values[0];  
        pgbar.setProgress(value);  
    }  
}

MainActivity.java:

public class MyActivity extends ActionBarActivity {  
  
    private TextView txttitle;  
    private ProgressBar pgbar;  
    private Button btnupdate;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        txttitle = (TextView)findViewById(R.id.txttitle);  
        pgbar = (ProgressBar)findViewById(R.id.pgbar);  
        btnupdate = (Button)findViewById(R.id.btnupdate);  
        btnupdate.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                MyAsyncTask myTask = new MyAsyncTask(txttitle,pgbar);  
                myTask.execute(1000);  
            }  
        });  
    }  
} 

Summary of this section:

Okay, at the beginning of this section, we introduced the concepts of application, process, thread, multithreading, asynchronous, and synchronous; then we explained why asynchronous operations are introduced in Android, and introduced the usage of AsyncTask. Of course, as mentioned above, asynchronous operations are used more in network operations. Later, when explaining network operations, this AsyncTask will be used. Stay tuned! This section ends here, thank you~