1. 说明
这篇文章首先先来看下AsyncTask的基本使用,然后我们会得到几个结论,最后我们再从源码的角度分析下我们所得到的几个结论,而且这几个结论肯定也是我们经常在网上边看到的。
2. 具体使用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Task().execute() ;
}
/**
* 以下方法:只有doInBackground()是运行在子线程中,其余都是运行在UI线程(主线程)
*/
class Task extends AsyncTask{
// 只要一调用 execute()方法,就会调用这个方法
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}
// 执行一些耗时操作:比如访问网络、读取数据库 ,这个方法是运行在 Thread ,子线程中的
@Override
protected Object doInBackground(Object[] params) {
return null;
}
// 执行完毕后返回的方法,也就是说等 doInBackground()获取到数据之后会把数据返回到这个方法里边
@Override
protected void onPostExecute(Object object) {
super.onPostExecute(object);
}
@Override
protected void onCancelled(Object object) {
super.onCancelled(object);
}
}
3. 结论
2.1>:AsyncTask只能执行一次,调用多次将会抛异常;
2.2>:只有只有doInBackground()是运行在子线程中,其余都是运行在UI线程(主线程);
4. 源码分析
验证一:为什么Task只能执行一次?
点击 task.execute()方法,进入源码:
private volatile Status mStatus = Status.PENDING;
@MainThread
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread
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;
}
分析以上源码可知:
刚进入AsyncTask时,mStatus 初始值是 Status.PENDING,就不会进入到if (mStatus != Status.PENDING)这个if语句,会直接向下边执行,会把状态置为mStatus = Status.RUNNING,同时就第一个执行onPreExecute()方法,当第二次再次调用execute()方法时,会进入之后会进入if (mStatus != Status.PENDING)这个if语句,此时是mStatus = Status.RUNNING,就会抛出异常;如果是 case FINISHED,同样会抛出异常;
这里就验证了,为什么AsyncTask只能执行一次,为什么一进来就会调用onPreExecute()方法
验证2:doInBackground()为什么会执行在子线程中?
接着上边的分析,
AsyncTask的部分源码如下:
mWorker.mParams = params;
exec.execute(mFuture);
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
mFuture = new FutureTask(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} 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);
}
}
};
}
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
FutureTask是实现RunnableFuture接口,所以FutureTask是一个接口,可以直接在FutureTask中查看run()方法,然后最终会调用 在子线程中
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
由上边可以知道,WorkerRunnable肯定是一个子线程,所以doInBackground()是运行在子线程中的;
执行完 doInBackground()后会返回一个 result,然后会执行postResult()方法,
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
postResult()方法 会在线程中 通过handler的消息机制,发一个消息,让其切换到主线程中,这个时候已经进入主线程中;
消息发完后会执行:
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult> result = (AsyncTaskResult>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
然后调用 finish()方法:
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
在finish()方法中会去判断有没有取消,如果取消了就会调用onCancelled(result)方法,否则就调用onPostExecute(result)方法,因为这里是通过handler发送消息让其切换至主线程中,所以这两个方法都是运行在主线程中,最终会把状态置为mStatus = Status.FINISHED;
总结
点击execute()方法后,就会去判断状态,如果状态不对就会抛异常,然后会把状态置为Running,然后执行onPreExecute()方法,执行完毕后会开一个线程执行 doInBackground()方法,执行完毕之后会利用 handler发送消息切换到主线程中,然后执行onPostExecute()或者onCancelled()方法,最后把状态置为Status.FINISHED即可;
这个就是整个流程。