Introduction
Android provides us with a lightweight asynchronous task class AsyncTask. This class implements asynchronous operations and provides interfaces to feedback the current asynchronous execution results and progress. Among these interfaces, there are those that run directly in the main thread (such as onPostExecute, onPreExecute, etc.).
AsyncTask can easily and correctly use UI threads. This class allows you to operate in the background and does not need to use threads or handlers to publish the results to the UI thread.
AsyncTask was designed to assist Thread and Handler, and it does not generate threads. AsyncTask should be used for short operations (up to a few seconds). If you want to keep threads running for a long time, use Executor or ThreadPoolExecutor or FutureTask.
AsyncTask runs tasks in the background, publishes results in the UI thread, defines three parameters, Params, Progress and Result, and performs four steps, onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
How to use
AsyncTask must be inherited to use. Subclasses must implement at least one method(ddoInBackground(Params…))
, There is also the most commonly used method(onPostExecute(Result)
。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = ; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += (urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
Start an asynchronous task:
new DownloadFilesTask().execute(url1, url2, url3);
AsyncTasks' paradigm parameters
The parameters used by asynchronous tasks are:
- Params, parameters passed in when starting a task
- Progress, the progress type published to the UI thread when the background task is executed
- Result, the result of the execution of background tasks
These three parameters do not necessarily have to be specified, you can use Void to pass in null values.
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
4 steps
-
onPreExecute()
, called on the UI thread before the application is executed. This step is usually used to prepare for the task to start, such as displaying a progress bar. -
doInBackground(Params…)
,existonPreExecute()
This method is executed immediately after the method is called and used to perform long-term tasks. - The parameters will be passed in this step, and the final result must be returned. You can use it on this page
publishProgress(Progress...)
To publish progress, these values are published in the UI thread,onProgressUpdate(Progress...)
take over.onProgressUpdate(Progress…)
, existpublishProgress(Progress...)
This method is called in the UI thread after the method is called. Execution time is not defined. This method is used to display progress in the user interface while the background calculation is still being executed. For example, it can be used to animate progress bars or display logs in text fields. -
onPostExecute(Result)
, after the background calculation is completed, call it on the UI thread. The result of the background calculation is passed to this step as a parameter.
Cancel asynchronous tasks
Can be called at any timecancel(boolean)
Method to cancel the task.
Calling this method will result inisCancelled()
The subsequent calls to return true.
After calling this method,onCancelled(Object)
, without callingonPostExecute(Object)
To cancel the task as quickly as possible, you should alwaysdoInBackground(Object [])
Periodic inspectionsisCancelled()
return value (if possible).
Thread rules
- The AsyncTask class must be loaded on the UI thread.
- A task instance must be created on the UI thread.
- Must be called on the UI thread
execute(Params …)
- Do not call manually
onPreExecute()
,onPostExecute(Result)
,doInBackground(Params …)
,onProgressUpdate(Progress …)
。 - The task can only be executed once (if you try to execute the second time, an exception will be thrown).
Memory monitoring
AsyncTask ensures that all callback calls are synchronized, making the following operations safe without explicit synchronization.
- In the constructor or
onPreExecute()
Set the member field indoInBackground(Params …)
cited in . - exist
doInBackground(Params …)
Set the member field inonProgressUpdate(Progress …)
andonPostExecute(Result)
cited in .
Execution order
When first introduced, AsyncTasks was executed serially on a single background thread.
Starting with DONUT, this is changed to a thread pool that allows multiple tasks to operate in parallel.
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you really need parallel execution, you can call it using THREAD_POOL_EXECUTORexecuteOnExecutor(,Object [])
。
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.