详细说明:
Handler 常用来多线程之间传递消息,AsyncTask 内部实现 InternalHandler,用来发送和处理消息 MESSAGE_POST_RESULT、MESSAGE_POST_PROGRESS,对应 AsyncTask 的回调方法 onProgressUpdate 和 onPostExecute,这两个方法都是要在 UI 线程回调的。示例是一个求和程序,用 Thread. sleep来模拟耗时的操作,执行结果如下
04-01 16: 12: 02.041 7203-7203/com. example test myappLication D/jeff:
onPreExecute
04-01 16: 12: 02.041 7203-7341/com. example test myapplication D/jeff:
doInBackg round:计算1到5之和
04-01 16: 12: 02.051 7203-7203/com. example test myapplication D/jeff:
onProgressUpdate: 1
04-01 16: 12: 03.061 7203-7203/com. example test myapplication D/jeff:
on ProgressUpdate: 2
04-01 16: 12: 04.061 7203-7203/com examp Le test myappLication D/jeff
onProgressUpdate: 3
04-01 16: 12: 05.061 7203-7203/com. example test myapplication D/jeff:
on ProgressUpdate: 4
04-01 16: 12: 06.061 7203-7203/com. example. test, myapplication D/jeff:
on ProgressUpdate: 5
04-01 16: 12: 07.051 7203-7203/com. example test myapplication D/jeff:
on PostExecute:计算结果=15
从结果看,依次回调 AsyncTask的 on Pre Execute、 doIn Background、
onProgressUpdate、 on PostExecute方法,其中 dolnBackground在子线程执行
(7203-7341),其他放都执行在主线程(7203-7203)。
AsyncTask回调方法
*Override this method to perform a computation on a
background thread, The
*k specified parameters are the parameters passed to ilink
#execute
k by the caller of this task.
半
This method can call ilink *pub lishProgress to publish
updates
k on the ur thread
k param params The parameters of the task
aWorkerThread
protected abstract Result doInBackg round Params.. params )
k Runs on the Ui thread before talink #dolnBackgroundh
/
Main Thread
protected void on PreExecute()t
/*
k Runs on the Ui thread after tlink #doInBackground, The
k specified result is the value returned by ialink
#doInBackg round].
*k
This method won 't be invoked if the task was cancelled
Runs on the Ui thread after tlink #cancel(boolean) is
invoked and
ialink #doInBackground (object[1) has finished.
k
The default imp lementation simply invokes ialink
#unCancelled( and
x ignores the result. If you write your own implementation, do
not call
super, onCancel led (result)
,
t param result The result, if any, computed in
ialink #doInBackground(object[))), can be null
SuppressWarnings(t"UnusedParameters"f)
Main Thread
protected void onCancelled(result result)t
on Cancelled()
/*米
*k
Applications shou ld preferably override ilink
ton Cancelled(object))
*k This method is invoked by the default imp lementation of
*k flink #on Cance l led(object)1.
k
Runs on the uI thread after falink *cancel(boolean)
invoked and
* iLink #doInBackground(object[) has finished.
Main Thread
protected void on Cancelled()t
doIn Background:这是一个抽象方法,所以必须要重写,运行在工作线程,
执行耗时操作,可以传递参数,在该方法中调用 publish Progress方法来通知
进度, on ProgressUpdate会接收进度
on Pre execute:执行在U线程,在 don Background前执行,一般做一些准
备工作
on PostExecute:执行在ω|线程,在 doIn Background后执行,接收
dolnBackground返回值,需要注意的是,如果任务被取消,改方法将不会被回
调
on ProgressUpdate:执行在U线程,接收迸度值,在 doIn Background中调
用 on ProgressUpdate方法后回调,如下载进度。
on Cancelled( Result):执行在U线程, AsyncTask调用 cancel方法之后回
调该方法,可以接收 doIn Background返回值,即时没有执行完。
on cancelled:同 on cancelled( Result)方法,区别在于不接收返回值。
、任务状态
public enum Status t
k Indicates that the task has not been executed yet
PENDING
/木木
k Indicates that the task is running
米
RUNNING
/
*k Indicates that ialink AsyncTask#onPostExecute) has
finished
FINISHED,
●PEND|NG:未执行
● RUNNING:执行中
●F|N|SHED:任务结束
四、执行流程分析
1.构造方法
public AsyncTask(Nullable Looper cal lbackLooper)t
mHandler cal lbackLooper = null cal LbackLooper =
Looper. getMainLooper()
getMainHandler()
new Hand ler(callbackLooper);
mWorker new WorkerRunnable
()i
public Result call() throws Exception t
mTaskInvoked. set(true
Result result nulLi
ry
Process. setThreadPriority( Process THREAD PRIORITY BACKGROUND
//noinspection unchecked
result doInBackg round(mParams);
Binder. flushPending Commands();
f catch (Throwable tr)i
cAncelled, set(true)
throw tr:
I finally t
postResult(result)i
eturn result
};
mFuture new FutureTask( mWorker)[
Override
protected void done()t
try t
c postResultI fNotInvoked (get())
f catch (InterruptedException e)t
android utiL. Log W(LOG TAG, e)
I catch ExecutionException e)t
throw new RuntimeException ("An error occurred
while executing doInBackg round(
e. getCause());
I catch CancellationException e)t
postResultIfNotInvoked(null):
}
三个很重要的变量, m Handler、 wOrker、 fUture,
private static class InternalHandler extends Handler t
public InternaLHandler( Looper looper)t
super(looper)
SuppressWarnings(t"unchecked
RawUseOfParameterizedType"1)
override
public void hand leMessage(Message msg)t
AsyncTaskResult> result =(AsyncTaskResult>
Isg obI
switch (msg, what)t
case MESSAgE Post result
// There is only one result
result, mTask. finish(result, mData[o])i
break
case mESSAge Post progress
result. mTask. onProgressUpdate( result. mData
break
Handler常用来多线程之间传递消息, AsyncTask内部实现 Internalhandler,用来
发送和处理消息 MESSAGE_ POST RESULT、 MESSAGE_POST_ PROGRESS,对应
AsyncTask的回调方法 on ProgressUpdate和 on Post execute,这两个方法都是要
在U线程回调的。
wOrker是 Worker runnable的实例, Workerrunnable实现了 Callable接口,可
以返回执行结果,耗时方法 doInBackground在 Worker runnable的ca方法中执
行,执行完后得到执行结果,执行 postResult方法,将结果传递到ω丨线程
fUture是 FutureTask的实例,用来执行任务 wOrker,并重写了done方法,执
行 postResultlfNotInvoked。 FutureTask这里不再展开,简单的说,就是
FutureTask实现了 Runnable和 Future接口,可以执行 Runnable和 Future任务,
可以返回执行结果。
private void postResultIfNotInvoked Result result)i
final boolean was TaskInvoked mTaskInvoked get();
if ( was TaskInvoked)i
postResult(result)
FutureTask的done方法在任务执行过程中最后回调,这里重写的done方法中的
postResult| fNotInvoked方法只有当任务没有正常调用时才会执行,如果正常调
用, mTaskInyoked.set(true);将忽略。
2.任务执行 execute
MainThread
public final AsyncTask
execute( Params., params)t
return executeOnExecutor( sDefaultExecutor, params
MainThread
public final AsyncTask
executeOn Executor( Executor exec,
Params.. params)t
if (sTatus ! Status, PENDING)
switch (sTatus)t
case running
throw new ILlegalStateException ("Cannot execute
task:
the task is already running. ")i
case fINished
throw new Illega lStateException("Cannot execute
task:
the task has a lready been executed
(a task can be executed onl
once)")
sTatus =Status. RUNNING;
on PreExecute()i
Worker pArams params i
exec, execute(mFuture)
return this
AsyncTask调用 execute方法来执行任务,如 wt execute(1,5)。我们重点分析一下
execution Executor这个方法,其中第一个参数是 Executor,异步任务执行器,用
来执行异步任务,默认用的是 sDefaultexecutor,且看 sDefaultexecutor是如何生
成的