1.1) The instance of the task must be created in the UI thread
2) The Execute method must be called in the UI thread
3) do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4) The task can only be executed once, otherwise an exception will occur when multiple calls are made.
If the call OnPreExecute () created in the child thread is also executed in the child thread that created the Asynctask, Doinbackground (Params ...) Execute in child threads, OnPostExecute (Result) and Onprogressupdate (Progress ...) In the main thread
2. The Asynctask object is not reusable, meaning that a Asynctask object can only execute () once, otherwise an exception is thrown "Java.lang.IllegalStateException:Cannot Execute task: The task is already running "
Asynctask source code is as follows:
@MainThread public final Asynctask<params, Progress, result> executeonexecutor (Executor exec, params ... params) { C0/>if (Mstatus! = status.pending) { switch (mstatus) {case RUNNING: throw new IllegalStateException (" Cannot execute task: " +" The task is already running. "); Case finished: throw new IllegalStateException ("Cannot execute task:" + "The task has already been executed"
+ "(a task can be executed only once)"); } } mstatus = Status.running;onpreexecute (); Mworker.mparams = params; Exec.execute (mfuture); return this; }
3. Check the return value of iscancelled () in Doinbackground () If your asynchronous task can be canceled.
Cancel () simply sets an identity bit for the Asynctask object, and when cancel () is called, the only thing that happens is that the identity bit of the Asynctask object has changed, and after Doinbackground () execution is complete, onpostexecute () It's not going to be recalled.
Doinbackground () and onprogressupdate () will continue to execute until the end of Doinbackground (). So the return value of iscancellled () is constantly checked in Doinbackground (), and when it returns true, it stops executing,
Especially when there is a cycle.
Public Final Boolean Cancel (Boolean mayinterruptifrunning) {
Mcancelled.set (TRUE);
Return Mfuture.cancel (mayinterruptifrunning);
}
4. If you want to use the network in the application, do not forget to declare the Internet permissions in the Androidmanifest, otherwise it will be reported strange exception information, such as the above example, if the Internet permission to take off will be thrown " Unknownhostexception ".
Compare Java SE's thread
Thread is a very primitive class, it has only a run () method, once started, cannot stop, it is only suitable for a very independent asynchronous task, that is, do not need to interact with the main thread, for other situations, such as the need to cancel or interact with the main thread, you need to add additional code to implement,
and also pay attention to the problem of synchronization. The Asynctask is packaged and can be used directly, if you only perform standalone asynchronous tasks, you can implement only Doinbackground ().
Therefore, when there is a very independent task, you can consider using thread, other times, as much as possible with Asynctask.
5. The use of Asynctask is usually accomplished by inheriting the superclass, such as:
Class Backgroundtask extends Asynctask<object,object,object> { @Override protected Object Doinbackground (Object ... params) { return null; }}
Subclasses must overload the Doinbackground method. The three types in <>, which in turn represent the type of execution parameter, the type of progress parameter, and the result parameter type. The parameter type of the Doinbackground must be the type of the execution parameter, the type must be returned, and the result parameter type.
These three types should be based on the need to decide, in fact, with object can also be used when doing type conversion. Start a asynctask that can be done in this way:
Backgroudtask BT = new Backgroundtask ();
Bt.execute ("param");
The easy mistake of using asynctask is to manipulate the UI elements directly inside the Doinbackground method. If you need to interact with the UI, you can work with publishprogress and Onprogressupdate. Like what
@Overrideprotected object Doinbackground (Object ... params) { ... Publishprogress ("20%"); ... Publishprogress ("80%"); ... return null;} protected void Onprogressupdate (Object ... progress) { ... Textview1.settext (String) progress[0]); ...}
The
Here onprogressupdate is working on the UI thread. Another issue with the
using Asynctask is about cancel. In fact, simply calling the Cancel method of the Asynctask object does not stop the Doinbackground method from continuing. The usual way to do this is to set a flag bit,
which is to check the value of a variable before each execution (or you can call the IsCancelled method) to decide whether to continue or stop. This approach is useful for some cyclical work, but may not be effective for some of the less cyclic work.
This is also a weakness of asynctask. Compared to thread, Asynctask also has a weakness is the problem of efficiency, this can be found in the link at the beginning of this article to find relevant information.
6. Asynctask There is also a problem related to the onpreexecute approach. This method is working on the UI thread. Although it is called OnPreExecute, the Doinbackground method (that is, actually execute) does not wait for the OnPreExecute method to finish all operations before it begins execution.
Therefore, generally do not use this method, you can call the Asynctask object's Execute method before the completion of the completed operation, so as not to cause some errors.
Asynctask also has a method of OnPostExecute, which is also working on the UI thread, which is called after the Doinbackground method executes and returns the result. This method can invoke the UI thread's startactivity, so that after a large number of background operations can be done, the
automatically jump activity function. This method can also execute another Asynctask's Execute method.
7. Order of execution:
Executed through Asynctask.execute ()
<1.6: Before 1.6 (donut): In the first version of Asynctask, the task is a serial dispatch. One task execution completes another to execute. The use of multiple asynctask may pose some problems due to serial execution of tasks.
So this is not a good way to handle asynchronous (especially when you need to work with the results on the UI)
1.6--2.3: All tasks are executed concurrently, which can lead to a situation where one of the tasks performs a problem and causes errors in other tasks.
> 3.0:asynctask is modified for sequential execution, and a new function Executeonexecutor (Executor) is added, and if you need to execute in parallel, you only need to call the function and set the parameters to execute in parallel.
Parallel Execution Asynctask.executeonexecutor (Executors.newfixedthreadpool (7), "");
Asynctask.executeonexecutor (Asynctask.thread_pool_executor) You can also use the thread pool provided by this system to handle your tasks.
By default, this thread pool is a concurrent processing task, that is, not in order. Core 5, Maximum 128
Android Asynctask usage Precautions and summary