Android Summary of defects and problems of AsyncTask
In Android development, AsyncTask can enable users to avoid directly using the Thread class and Handler to handle background operations, which is suitable for situations where data needs to be processed asynchronously and updated to the interface. AsyncTask is suitable for short-term operations with only a few seconds of background operations. However, AsyncTask itself has many bad problems. If you are not careful during use, it will affect the robustness of the program.
1. Life cycle
Many developers will think that an AsyncTask created in an Activity will be destroyed as the Activity is destroyed. However, this is not the case. AsyncTask will be executed until the doInBackground() method is executed. Then, if cancel(boolean) is called, the onCancelled(Result result) method will be executed; otherwise, the onPostExecute(Result result) method will be executed. If our Activity is not cancelled before it is destroyed, this may cause our AsyncTask to crash (crash). Because the view it wants to deal with no longer exists. So, we always have to make sure that tasks are cancelled before the activity is destroyed. In short, we need to make sure that AsyncTask is cancelled correctly.
In addition, even if we call cancer() correctly, it may not be possible to actually cancel the task. Because if there is an uninterruptible operation in doInBackgroud, such as (), then this operation will continue.
2. Memory leak
If AsyncTask is declared as a non-static inner class of the Activity, then AsyncTask retains a reference to the Activity that created the AsyncTask. If the Activity has been destroyed and the background thread of AsyncTask is still executing, it will continue to retain this reference in memory, causing the Activity to be recycled and causing memory leakage.
3. The result is lost
Screen rotation or Activity is killed by the system in the background, etc., will lead to the recreation of Activity. The previously run AsyncTask will hold a reference to the previous Activity, which is invalid. At this time, calling onPostExecute() and then updating the interface will no longer take effect.
4. Parallel or serial
In versions before Android 1.6, AsyncTask is serial, and in versions 1.6 to 2.3, it has been changed to parallel. The version after 2.3 has been modified to support parallelism and serialization. When you want to execute serially, execute() method directly. If you need to execute in parallel, executeOnExecutor(Executor) must be executed.
Thank you for reading, I hope it can help you. Thank you for your support for this site!