Welcome Reprint, please attach Source:
http://blog.csdn.net/as02446418/article/details/47684415
The comments are written in the code, just look at the code:
/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "Licen Se "); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */ PackageAndroid.os;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.LinkedBlockingQueue;ImportJava.util.concurrent.ThreadFactory;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.FutureTask;ImportJava.util.concurrent.ExecutionException;ImportJava.util.concurrent.TimeoutException;ImportJava.util.concurrent.CancellationException;ImportJava.util.concurrent.atomic.AtomicInteger;/** * Asynctask can make it easier to manipulate the UI thread, Asynctask can result in a time-consuming operation that results in updating the UI thread without relying on handler, etc. </p> * an Asyntask is able to perform time-consuming calculations in the background and then feed the results back to the UI thread, the entire operation is asynchronous, and the async task has a total of three class properties params, Progress and Result, * and 4 steps, respectively Begin,doinbackground , Processprogress and end. * * Asynctask need to rewrite at least one method--doinbackground, most often with onpostexecute. * Three class Attributes * 1.Params, when the task starts to pass the parameters of the task * 2.Progress, when the background calculation of the published real-time progress * 3.Result, the results of the background calculation * Use Asynctask need to meet the conditions: * 1. The task must be created in the UI thread * 2. Using the Execute method must be in the UI thread * 3. Do not show Onpreexecute,onpostexecute,doinbackground,onprogressupdate * 4. The task can only be exceute once, or it will throw an exception * /PublicAbstract class asynctask<Params, Progress, Result> { PrivateStaticFinalString Log_tag ="Asynctask";PrivateStaticFinalint core_pool_size =5;PrivateStaticFinalint maximum_pool_size = -;PrivateStaticFinalint keep_alive =1;//block queue PrivateStaticFinalBlockingqueue<runnable> Sworkqueue =NewLinkedblockingqueue<runnable> (Ten);PrivateStaticFinalThreadfactory sthreadfactory =NewThreadfactory () {//Atomic interger count variable Private FinalAtomicinteger MCount =NewAtomicinteger (1);//Count the number of threadsPublic Thread Newthread (Runnable r) {return NewThread (R,"Asynctask #"+ mcount.getandincrement ()); } };//Defines a thread pool PrivateStaticFinalThreadpoolexecutor Sexecutor =NewThreadpoolexecutor (Core_pool_size, Maximum_pool_size, Keep_alive, Timeunit.seconds, SWorkQueue, SThreadFactory) ;PrivateStaticFinalint Message_post_result =0x1;PrivateStaticFinalint message_post_progress =0x2;PrivateStaticFinalint message_post_cancel =0x3;//Inherited handler class, internally implemented by handler PrivateStaticFinalInternalhandler Shandler =NewInternalhandler ();Private FinalWorkerrunnable<params, result> Mworker;//futuretask container, storage result type Private FinalFuturetask<result> mfuture;PrivateVolatile Status mstatus = status.pending;/** * Enumeration that indicates the current state of the task, and the task can only be in one state * /public enum Status {/** * Suspended status, not yet started task * /PENDING,/** * Operation status indicates that the status is in progress */RUNNING,/** * End status indicates the status is complete */Finished,}/** * Create Asynctask, re-declare: can only be created in the UI thread */Public Asynctask () {mworker =NewWorkerrunnable<params, result> () {public Result call ()throwsException {process.setthreadpriority (process.thread_priority_background);returnDoinbackground (Mparams); } }; Mfuture =NewFuturetask<result> (Mworker) {@Override protectedvoid done () {message message; Result result =NULL;Try{result = get (); }Catch(Interruptedexception e) {ANDROID.UTIL.LOG.W (Log_tag, E); }Catch(Executionexception e) {Throw NewRuntimeException ("An error occured while executing doinbackground ()", E.getcause ()); }Catch(Cancellationexception e) {message = Shandler.obtainmessage (Message_post_cancel,NewAsynctaskresult<result> (Asynctask. This, (result[])NULL)); Message.sendtotarget ();return; }Catch(Throwable t) {Throw NewRuntimeException ("An error occured while executing"+"Doinbackground ()", t); } message = Shandler.obtainmessage (Message_post_result,NewAsynctaskresult<result> (Asynctask. This, result)); Message.sendtotarget (); } }; }/** * Get the current status of the task * * @return the present status. */PublicFinalStatus GetStatus () {returnMstatus; }/** * This is Doinbackground's abstract way. * * @see #onPreExecute () * @see #onPostExecute * c3> @see #publishProgress * / protected AbstractResult Doinbackground (params ... params);/** * * * * @see #onPostExecute * @see #doInBackground * * before Doinbackground protectedvoid OnPreExecute () {}/** * Executes after doinbackground, returns null if the task is canceled or throws an exception * * @see #onPreExecute * @see #do Inbackground * * @SuppressWarnings({"Unuseddeclaration"})protectedvoid OnPostExecute (Result result) {}/** * Executes after the publishprogress call, where the values of the parameters are passed to publishprogress * * @see #publishProgress * @s EE #doInBackground * / @SuppressWarnings({"Unuseddeclaration"})protectedvoid Onprogressupdate (Progress ... values) {}/** * The method that executes after cancel () is called * * @see #cancel (Boolean) * @see #isCancelled () */ protectedvoid Oncancelled () {}/** * Returns True if the task is canceled before the normal end, otherwise false * /PublicFinalBoolean iscancelled () {returnMfuture.iscancelled (); }/** * Attempt to cancel a task that may fail on the way if the task has already been completed, or has been canceled, or for other reasons, * if this method is called before the task is started, the task will not start, if called after startup, the parameter passed in Mayinterrupti Frunning decides whether to terminate the task while the task is running * @see #isCancelled () * @see #onCancelled () */PublicFinalBoolean Cancel (Boolean mayinterruptifrunning) {returnMfuture.cancel (mayinterruptifrunning); }/** * Wait until the result is complete and return the result * * @return the computed result. * * @throws cancellationexception If the computation was cancelled. * @throws executionexception If The computation threw an exception. * @throws interruptedexception If The current thread is interrupted * while waiting. */PublicFinalResult get ()throwsInterruptedexception, Executionexception {returnMfuture.get (); }/** * Wait until the end of timeout to check the results, regardless of whether the task has been completed, usually put on time-consuming tasks * * @param timeout time to wait before cancelling the Operation. * @param Unit The time unit for the timeout. * * @return the computed result. * * @throws cancellationexception If the computation was cancelled. * @throws executionexception If The computation threw an exception. * @throws interruptedexception If The current thread is interrupted * while waiting. * @throws timeoutexception If The wait timed out. */PublicFinalResult get (long timeout, timeunit unit)throwsInterruptedexception, Executionexception, timeoutexception {returnMfuture.get (timeout, unit); }/** * Returns Asynctask<params, Progress, result> objects that need to be executed in the UI thread * * * @param Params the Parame Ters of the task. * * @return This instance of Asynctask. * * @throws illegalstateexception If {@link #getStatus ()} returns either * {@link asynctask.status#running} or {@link asynctask.status#finished}. */PublicFinalAsynctask<params, Progress, result> execute (params ... params) {if(Mstatus! = status.pending) {switch (mstatus) { CaseRUNNING:Throw NewIllegalStateException ("Cannot execute task:"+"The task is already running."); CaseFinished:Throw NewIllegalStateException ("Cannot execute task:"+"The task has already been executed"+"(a task can be executed only once)"); }} mstatus = status.running; OnPreExecute (); Mworker.mparams = params; Sexecutor.execute (mfuture);return This; }/** * This method is called by Doinbackground and represents the current completed status * * @see #onProgressUpdate * @see #doInBackg Round * * protected Finalvoid Publishprogress (Progress ... values) {shandler.obtainmessage (message_post_progress,NewAsynctaskresult<progress> ( This, values). Sendtotarget (); }/** * This method is automatically called internally during task tasks * / Privatevoid finish (Result result) {if(iscancelled ()) result =NULL; OnPostExecute (result); Mstatus = status.finished; }/** * This is the most important internal implementation of the handler, according to different MSG to distribute different operations * / PrivateStatic class internalhandler extends Handler { @SuppressWarnings({"Unchecked","Rawuseofparameterizedtype"})@Overridepublic void Handlemessage (Message msg) {asynctaskresult result = (Asynctaskresult) msg.obj; Switch (msg.what) { CaseMessage_post_result://There is only one resultResult.mTask.finish (result.mdata[0]); Break; CaseMESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate (Result.mdata); Break; CaseMESSAGE_POST_CANCEL:result.mTask.onCancelled (); Break; } } }PrivateStaticAbstract class workerrunnable<Params, Result> implements Callable<Result> {Params[] Mparams; }@SuppressWarnings({"Rawuseofparameterizedtype"})PrivateStatic class asynctaskresult<Data> { FinalAsynctask Mtask;FinalData[] Mdata; Asynctaskresult (asynctask task, data ... data) {mtask = task; Mdata = data; } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Asynctask Source parsing