Android can only do UI operations in the main thread, and if it is another child thread, it needs to be handler by the asynchronous message processing mechanism. In addition, there is a very convenient asynctask class, which encapsulates the handler and thread pools internally. This paper first briefly introduces the usage of Asynctask, and then analyzes the concrete implementation.
Basic usage
Asynctask is an abstract class, we need to create subclasses to inherit it, and rewrite some methods. Asynctask accepts three generic parameters:
Params: Specifies the type of parameter to be passed to the task execution
Progress: Specifies the parameter types that return task progress to the UI thread when the background task executes
Result: Specifies the type of results returned after the task completes
In addition to specifying generic parameters, you need to rewrite some methods as needed, often as follows:
OnPreExecute (): This method is invoked on the UI thread to do some initialization before the task executes, such as displaying the load progress control on the interface
Doinbackground: Called immediately after the end of OnPreExecute () in the background thread for time-consuming operations. In this method, you can call the Publishprogress method to return the execution progress of a task
Onprogressupdate: Called after doinbackground call Publishprogress, working on UI thread
OnPostExecute: Background task is called after the end, working on the UI thread
Source Analysis
The following analysis of the implementation of this class, mainly has a thread pool and Handler two parts.
1. Thread pool
when a asynctask is executed, the Execute () method is invoked, starting at this point:
Public final Asynctask<params, Progress, result> execute (Params ... Params) {return
executeonexecutor ( Sdefaultexecutor, params);
Public final Asynctask<params, Progress, result> executeonexecutor (Executor exec,
Params ... Params) {
if (Mstatus!= status.pending) {
switch (mstatus) {case
RUNNING:
throw new IllegalStateException ("Cannot execute task:" + "the task is Alre Ady 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;
Execute OnPreExecute
onpreexecute () first;
Mworker.mparams = params;
Exec.execute (mfuture);
return this;
The Execute method invokes Executeonexecutor. In this method, first check whether the task has been executed or finished, and then mark the task as running. The first thing to do is OnPreExecute, and then assign the parameter to the Mworker object. This mworker is a callable object that is eventually packaged as a futuretask and the code is as follows:
private static abstract class Workerrunnable<params, result> implements callable& Lt
result> {params[] mparams; Mworker = new Workerrunnable<params, result> () {public result call () throws Exception {Mtaskinvoked.set
(true);
Process.setthreadpriority (Process.thread_priority_background);
Noinspection unchecked return Postresult (Doinbackground (mparams));
}
}; Mfuture = new Futuretask<result> (mworker) {@Override protected void done () {try {Postresultifnotinvoke
D (get ());
catch (Interruptedexception e) {ANDROID.UTIL.LOG.W (Log_tag, E);
catch (Executionexception e) {throw new RuntimeException ("An error occured while executing doinbackground ()",
E.getcause ());
catch (Cancellationexception e) {postresultifnotinvoked (null);
}
}
};
As you can see from the code above, the call () method in the Mworker object calls Doinbackground, and the return value is given to the Postresult method, which sends a message through handler, which is later analyzed in detail.
After the Mworker object is encapsulated as Futuretask, it is executed by the thread pool, as can be seen from the Execute method, using Sdefaultexecutor, whose value defaults to Serial_executor, which is the serial executor, which is implemented as follows:
private static class Serialexecutor implements Executor {//Linear bidirectional queue to store all asynctask tasks
Final arraydeque<runnable> mtasks = new arraydeque<runnable> ();
The Asynctask task currently being performed Runnable mactive; Public synchronized void Execute (final Runnable R) {//Add a new Asynctask task to the bidirectional queue Mtasks.offer (new Runnable () {Publ
IC void Run () {try {///Execute Asynctask Task R.run ();
finally {///Current task execution completes next task Schedulenext ();
}
}
});
if (mactive = = null) {Schedulenext (); } protected synchronized void Schedulenext () {//takes the task of the queue header from the task queue and, if so, to the concurrent thread pool to execute if ((mactive = Mtasks.poll ())
!= null) {Thread_pool_executor.execute (mactive); }} public static final Executor thread_pool_executor = new Threadpoolexecutor (core_pool_size, Maximum_pool_size,
Keep_alive, Timeunit.seconds, Spoolworkqueue, sthreadfactory);
In the above code, if a task executes, the Serialexecutor Execute method is invoked, and its logic is to add the Runnable object to the Arraydeque queue and then determine if the Mactivie is empty. The first execution of mactive of course is empty, so the execution of Schedulenext, in fact, is to take out the first task in the queue of tasks to the thread pool (thread_pool_executor) execution. The Run method of the Runnable object that joins the Mtask queue will eventually call Schedulenext, and then the team head task will be taken out of the task queue. This enables single-threaded sequential execution, so the default enabled in Asynctask is single-threaded execution, which performs the next task only after the last task executes . If you want to enable multithreading to perform tasks, you can call Executeonexecutor (Executor exec, Params ... Params) directly, where the Executor parameter can be used asynctask the band Thread_pool_ EXECUTOR, you can also define your own.
2, Handler
Asynctask internally uses handler to deliver the message, which is implemented as follows:
private static class Internalhandler extends Handler {
@SuppressWarnings ({"Unchecked", "Rawuseofparameterizedtype "}"
@Override public
void handlemessage (Message msg) {
Asynctaskresult result = (Asynctaskresult) msg.obj;
switch (msg.what) {case
Message_post_result:
//There be only one result
result.mTask.finish ( Result.mdata[0]);
break;
Case message_post_progress:
result.mTask.onProgressUpdate (result.mdata);
break;
}
}
If the message type is a return value (Message_post_result) after the task executes, the finish () method is called:
private void finish (result result) {
if (iscancelled ()) {
oncancelled (result);
} else {
OnPostExecute (result);
}
Mstatus = status.finished;
}
As you can see from the above, if the task is canceled, call oncancelled, otherwise call OnPostExecute, so if a asynctask task is canceled, then OnPostExecute will not be executed.
If the message type is execution Progress (message_post_progress) will call Onprogressupdate, the method defaults to a null method, which we can rewrite according to our own needs.
Summarize
The main logic of Asynctask, as analyzed above, sums up a few points to note:
1), Asynctask class must be in the UI line Cheng (the system will help us to complete automatically from the beginning of 4.1)
2), the Asynctask object must be created in the UI thread
3), the Execute method must be called on the UI thread
4), do not manually invoke OnPreExecute (), Doinbackground, Onprogressupdate method
5), a task can only be called once (the second call throws an exception)
There are some other details can study the source code, in addition to recommend a few Good articles:
Android Asynctask completely parse, take you from the source point of view thoroughly understand