Asynctask official documents and tutorials

brief introduction

Android provides us with a lightweight asynchronous task class, asynctask. This class implements asynchronous operations and provides interfaces to feed back the current asynchronous execution results and progress. Some of these interfaces 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 without using threads or handlers to publish results to UI threads.

Asynctask is designed to assist threads and handlers, and will not generate threads. Asynctask should be used for operations in a short time (up to a few seconds). If you want to keep the thread running for a long time, please use executor or ThreadPoolExecutor or futuretask.

Asynctask runs the task in the background, publishes the results in the UI thread, defines three parameters, params, progress and result, and performs four steps: onpreexecute, doinbackground, onprogressupdate and onpostexecute.

usage method

Asynctask must be inherited for use. Subclasses must implement at least one method (ddoinbackground (params...)) and one of the most commonly used methods (onpostexecute (result).

Start asynchronous task:

Generic parameters for asynctasks

The parameters used by asynchronous tasks are:

These three parameters do not have to be specified. You can use void to pass in null values.

4 steps

Cancel asynchronous task

You can cancel the task at any time by calling the cancel (Boolean) method.

Calling this method will cause subsequent calls to iscancelled() to return true.

When this method is called, oncancelled (object) is used instead of onpostexecute (object)

In order to cancel the task as quickly as possible, the return value of iscancelled() should always be checked periodically from doinbackground (object []), if possible.

Thread rule

Memory monitoring

Asynctask ensures that all callback calls are synchronized, making the following operations safe without explicit synchronization.

Execution sequence

When first introduced, asynctasks executes 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 from Honeywell, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If parallel execution is really needed, thread can be used_ POOL_ Executor calls executeonexecutor (java.util.concurrent.executor, object []).

summary

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

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
分享
二维码
< <上一篇
下一篇>>