概念
AsyncTask是一种轻量型的异步任务类,可在线程池中执行后台任务,然后在UI线程中更新UI;它包含了两个线程池和一个Handler。
使用
它的使用比较简单,可以直接继承AsyncTask,然后实现它的方法,进而执行任务和更新UI,下面为它的四个重要的方法
AsyncTask是一个抽象类
public abstract class AsyncTask<Params, Progress, Result>;
- onPreExecute():在主线程中执行,在异步任务执行之前执行
- doInBackground(Params…params):在线程池中执行;执行后台任务,参数为调用execute方法时传进来的参数;它的返回值对应类上面的Result;可在其中调用publishProgress方法,publishProgress会调用onProgressUpdate(Progress…value)。
- onProgressUpdate(Progress…value):在主线程中执行,主要用于更新任务进度
- onPostExecute(Result result):在主线程中执行,传进来的参数为doInBackground方法的返回值。
下面为它的实际用法:
1.定义
public class MyAsyncTask extends AsyncTask<String,Long,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
//做准备
}
@Override
protected String doInBackground(String... strings) {
Long progress=0L;
for (int i = 0; i < strings.length; i++) {
//下载文件(多个)
progress=loadFile(strings[i]);
publishProgress(progress);
}
return "success!";
}
@Override
protected void onProgressUpdate(Long... values) {
super.onProgressUpdate(values);
setCurrentProgress(values[0]);//设置当前下载进度
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//提示执行结果
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
2.执行
new MyAsyncTask().execute("url1","url2","url3");
在使用过程中的限制
- AsyncTask类必须在主线程中加载;因为在AsyncTask中有个静态的Handler对象,主要是来执行onPostExecute方法;AsyncTask在主线程加载意味着这个Handler对象也在主线程中加载,所以就可以用来执行需要执行在主线程中的方法。
- AsyncTask的对象必须在主线程中创建
- execute方法必须在主线程中调用
- 不要在程序中直接调用以上几个方法
- 一个AsyncTask对象只能执行一次,即只能调用一次execute方法,否则会报错(源码中的executeOnExecutor方法可知)
AsyncTask的修改过程(串行与并行的使用)
1.6之前是串行(排队执行),1.6~3.0是并行(同时执行多个任务),3.0以后是串行,但是仍然可以用executeOnExecutor来进行并行。
工作原理
1. 从execute方法进入,可以知道里面调用了executeOnExecutor方法
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
//从这里可知为什么不可以执行execute方法多次
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方法,可作前期的准备工作
onPreExecute();
mWorker.mParams = params;
//exec是一个SerialExecutor对象
exec.execute(mFuture);
return this;
}
2. 在SerialExecutor中的execute方法:
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
//r为一个FutureTask对象,执行了run方法
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
//这里是一个线程池,添加要执行的任务
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
3. 查看了FutureTask的run方法可知里面执行了Callable的call方法;返回头看看AsyncTask的构造方法,里面初始化了WorkerRunable对象和FutureTask对象;并把WorkerRunable传给了FutureTask
//WorkerRunnable实现了Callable接口
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//这里执行了doInBackground,也就是开始执行任务
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//执行结束后执行此方法
postResult(result);
}
return result;
}
};
//mWorker作为参数,mFuture调用run方法相当于mWorker调用了call方法
mFuture = new FutureTask<Result>(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);
}
}
};
4. postResult方法(发送消息到InternalHandler)
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
//这里向IntentHandler发送消息
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
5. InternalHandler的定义
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
//接收了postResult方法里面发送过来的消息
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
//任务完成
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//还在执行,调用onProgressUpdate方法
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
由InternalHandler的定义可知,如果任务完成,便调用finish方法,如果还在执行中,便调用onProgressUpdate方法,这里证明了为什么AsyncTask要在主线程加载
6. finish方法(如果任务被取消了,则调用onCanceled方法,否则调用onPostExecute方法)
private void finish(Result result) {
if (isCancelled()) {
//如果任务是被取消了的
onCancelled(result);
} else {
//任务真正完成
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
以上是关于AsyncTask的使用及工作原理分析,希望喜欢的能够点个赞鼓励一下,同时有什么不好的地方欢迎吐槽。