Summary of defects and problems of Android asynctask

Summary of defects and problems of Android asynctask

In Android development, asynctask allows users to avoid directly using thread class and handler to process background operations. It is applicable to the situation that data needs to be processed asynchronously and updated to the interface. Asynctask is suitable for short-time operations with background operations of only a few seconds. However, asynctask itself has many bad problems. If you don't pay attention to it in use, it will affect the robustness of the program.

1. Life cycle

Many developers 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) method will be executed; Otherwise, execute the onpostexecute (result) method. If the asynctask is not cancelled before our activity is destroyed, it may crash our asynctask. Because the view it wants to handle no longer exists. Therefore, we must always ensure that the task is cancelled before the destruction activity. In conclusion, we need to ensure that asynctask is cancelled correctly when using asynctask.

In addition, even if we call cancle () correctly, it may not really cancel the task. Because if there is an uninterrupted operation in doinbackground, such as bitmapfactory. Decodestream(), the operation will continue.

2. Memory leak

If asynctask is declared as a non static internal class of an activity, asynctask will retain 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 keep this reference in memory, so that the activity cannot be recycled, resulting in memory leakage.

3. Result loss

The screen rotation or the system killing the activity in the background will lead to the re creation of the activity. The previously run asynctask will hold a reference to the previous activity, which is no longer valid. In this case, calling onpostexecute() to update the interface will no longer take effect.

4. Parallel or serial

In versions before Android 1.6, asynctask was serial. In versions 1.6 to 2.3, it was changed to parallel. The version after 2.3 has been modified to support parallel and serial. When you want serial execution, you can directly execute the execute () method. If parallel execution is required, you need to execute the executeonexecutor (executor).

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>