Complete AsyncTask parsing (based on 7.0) and asynctask parsing 7.0
In normal development, asynchronous operations are very common. You often need to refresh the UI after executing asynchronous tasks. This requires Android Asynchronous Message Processing Mechanism Handler, of course, we can also use AsyncTask. I believe you have used AsyncTask more or less.
Basic usage:
Three generic types: AsyncTask <Params, Progress, Result>
1. params: the input parameters for starting a task, such as the HTTP request URL and the data type required for executing the task. progress: Progress type of the background task execution Progress. result: The final Result type returned by the asynchronous task.
Several common methods:
protected void onPreExecute() {}
Run in the UI thread. Generally, some UI operations are performed before the asynchronous task is executed.
protected Result doInBackground(Params … params) {}
It is executed in an asynchronous thread, and time-consuming operations are executed in this method. The returned results are passed to onPostExecute (). When the task is executed, publishProgress () is called to pass the execution progress to onProgressUpdate ()
protected void onProgressUpdate(Progress … progresses) {}
It is executed in the UI thread, updates the progress information, and is called back when publishProgress () is called.
protected void onPostExecute(Result result) {}
Run in the UI thread. Generally, after the background task is executed, the UI operations and display results are updated.
protected void onCancelled() {}
Executed in the UI thread, cancel () is called Source code process
The specific usage will not be shown here. Next, let's look at the source code. First, let's look at the constructor in the new AsyncTask:
Constructor
Public AsyncTask () {mWorker = new WorkerRunnable
() {Public Result call () throws Exception {mTaskInvoked. set (true); // set the flag location mTaskInvoked to true Result = null; try {Process. setThreadPriority (Process. THREAD_PRIORITY_BACKGROUND); // set the thread priority to 10: Priority 1-10. A greater value indicates a higher priority. The default value is 5. Binder. flushPendingCommands (); // callback doInBackground (), input parameter} catch (Throwable tr) {mCancelled. set (true); throw tr;} finally {postResult (result); // the return value of doInBackground () is sent to postResult ()} return result ;}; mFuture = new FutureTask
(MWorker) {@ Override protected void done () {try {postResultIfNotInvoked (get (); // get () is the result of task execution} catch (InterruptedException e) {android. util. log. w (LOG_TAG, e);} catch (ExecutionException e) {throw new RuntimeException ("An error occurred while executing doInBackground ()", e. getCause ();} catch (CancellationException e) {postResultIfNotInvoked (null );}}};}
There are two important objectsMWorker andMFuture. First, seeMWorker isInternal Class Object of WorkerRunnable type:
Private static abstract class WorkerRunnable
Implements Callable
{Params [] mParams;} public interface Callable
{/*** Computes a result, or throws an exception if unable to do so. * When a result is calculated and cannot be executed, an Exception is thrown * @ return computed result * @ throws Exception if unable to compute a result */V call () throws Exception ;}
Analyze the inheritance relationship, and finallyWorkerRunnableCallable interface, which has only oneThe Return Value Type of the call () method is generic. Because whether it is inheritanceThread class or implementationThe Runnable method cannot directly return results after the task is executed. WhileThe Callable interface makes up for this defect whenAfter the call () method is executed, a generic object is returned.MWorker is rewritten.I added a comment to the internal implementation of the call method.
Then analyzeFutureTask, which implementsRunnableFuture interface,RunnableFuture is ultimately inheritedRunnable andFuture Interface
public interface RunnableFuture extends Runnable, Future { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ void run();}
Runnable interfaceFutureTask can be executed by Thread,Future The interface is mainly for Runnable and Callable tasks. Three functions are provided: Determine whether the task is completed, interrupt the task, and obtain the task execution result.
mAsyncTask().execute();
Start from the starting point for executing the asynchronous task and start with the execute method:
public final AsyncTask execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params);}public final AsyncTask executeOnExecutor(Executor exec, Params... params) { 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;}
Row 5: if the task is running or completed, an exception is reported, that is, each task can be executed only once.
Row 17: onPreExecute () is executed and is still in the main thread.
Row 18: Use mWorker. mParams to save the input parameters.
Row 19: Call the execute () method of the passed-In Executor type parameter exec and pass mFuture in. exec is the sDefaultExecutor in the execute () method.
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;public static final Executor SERIAL_EXECUTOR = new SerialExecutor();private static class SerialExecutor implements Executor { final ArrayDeque mTasks = new ArrayDeque (); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } }}
SDefaultExecutor is an instance of the SerialExecutor class. The SerialExecutor maintains an ArrayDeque queue mTasks.
Line 7: add the incoming mTask to mTasks.
Lines 16-17: