1. Introduction

AsyncTask is a common multithreaded asynchronous task component developed by Android.

Why use a component for multithreaded asynchronous tasks? This is because the main thread of an Android application (also called the UI thread) does not allow time-consuming operations to be performed in this thread. Such as loading large images, accessing the web and so on. If the main thread is occupied for more than 5 seconds, there will be an Application Not Response (ANR) exception, that is, many years ago when the Android device configuration is Not good, the Application does Not respond, whether to wait for the situation.

Although it is now rarely used except for the need to display the download progress when downloading. But as a component of the Android framework, it’s important to know something about AsyncTask.

2. Show

2.1 Parameter Description

We need to write a class that inherits from AsyncTask. AsyncTask has three data types, which can be customized. So what do these three data types represent? ,progress,result>

  1. The first data type Params: specifies the data type of the parameter passed in doInBackground. Used to specify the data type of execute in mytask.execute (Params).

  2. The second data type Progress: specifies the data type of onProgressUpdate(Integer values).

  3. The third data type Result: specifies the data type of the value returned in doInBackground. Used to specify the data type of the parameter passed in onPostExecute.

2.2 Method Description

With parameters out of the way, it’s time to talk about methods in AsyncTask.

  1. OnPreExecute () : executes on the main thread. This method is the first method executed by AsyncTask and can be used to initialize and prepare the call to the doInBackground method.

  2. doInBackground(Params… Params): executes in child threads. This method is the focus of AsyncTask, where you need to implement all of your time-consuming operations. When this method ends, the return value is returned to the main thread

  3. publishProgress(Progress… Values): executed in a child thread. This method is used for invocation, not overwriting. This method is used to notify updated progress information. Call this method every 5% if you want to update the current progress every 5%.

  4. onProgressUpdate(Progress… Values): executed in the main thread. This method is used to update the progress information in the View, so this method is called in the main thread.

  5. OnPostExecute (Result Result): execute in the main thread. This method is used to update the last View on the value returned by doInBackground.

Of the above methods, only the doInBackground method is the only abstract method that must be overridden. If you just want to do tasks that take time but don’t require progress, you can just override doInBackground.

2.3 Execution Method description

And then finally the AsyncTask is executed. Using the example code above as an example, MyTask().execute(“Hello world”) will rest for 5 seconds and return Hello World PEACE! Results.

If you want to retrieve the returned value, you can retrieve it by val reuslt = MyTask().execute(“Hello world”).get()

It is important to note that if AsyncTask references a View component, such as a TextView component, the Task must be cancelled when the Activity is destroyed to prevent memory leaks. The method is mytask.cancel (true).

3. sample code

class MyTask: AsyncTask<String, Int, String>() {override fun onPreExecute() {super.onpreexecute () log.d ("MyTask", "OnPreExecute ") binding.textview.text = "MyTask onPreExecute"} String?) : String { Log.d("MyTask", "doInBackground") for (i in 0.. 100) { Thread.sleep(50) publishProgress(i) } var result = "PEACE!" params[0]? Return result} // Override fun onProgressUpdate(vararg values: Int? {super.onProgressupDate (*values) bind.textView.text = "${values[0]} %"}  String?) { super.onPostExecute(result) Log.d("MyTask", "onPostExecute") binding.textView.text = "MyTask onPostExecute" } }Copy the code

4. Simple principle description

The source code analysis will not be expanded in detail, estimated that we do not want to see. This section describes the implementation principle of AsyncTask. Since AsyncTask switches between the main thread and child thread, it is implemented internally by a Handler. Thread management uses Java’s thread pool ThreadPoolExecutor and Java’s concurrent blocking queue LinkedBlockingQueue for thread control management.

Making: github.com/HyejeanMOON…