AsyncTask是一个抽象的泛型类,它提供了三个参数。其中Params表示在执行AsyncTask时所需要输入的参数类型例如:URL类型,Progress表示后台任务执行的进度的类型例如:Integer,Result表示后台任务的返回结果的类型例如:Boolean,如果不需要传入具体参数则都可以使用Void代替。
public abstract class AsnycTask<Params,Progress,Result>
AsyncTask提供了4个核心方法,含义如下所示:
(1)onPreExecute(),在主线程中执行,异步任务开始执行前调用,通常做一些准备准备任务,例如显示一个进度条。
(2)doInBackground(Params…params),在线程池中执行,此方法用于执行异步任务,params参数表示异步任务的输入参数。在此方法中可以通过publishProgress方法来更新任务的进度,publishProgress方法会调用onProgressUpdate方法,另外此方法需要返回计算结果给onPostExecute方法。
(3)onProgressUpdate(Progress…values),在主线程中执行,当后台任务执行进度发生变化时此方法会被调用。
(4)onPostExecute(Result result),在主线程中执行,异步任务执行后,此方法会被调用,其中result参数表示后台任务的返回值,即doInBackground方法执行完成后的返回结果。
(5)onCancelled(),在主线程中执行,异步任务被取消时,此方法会被调用,而此时onPostExecute则不会被调用,onCancelled和onPostExecute只会执行一个。
访问网页:
class NewsAsyncTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
String responseData = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(params[0]).build();
try {
Response response = client.newCall(request).execute();
responseData = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return responseData;
}
@Override
protected void onPostExecute(String str) {
textView.setText(s);
}
}
可以通过如下方式启用NewsAsyncTask
new NewsAsyncTask().execute("http://www.baidu.com");
其中doInBackground方法返回值responseData即为onPostExecute方法的参数str;doInBackground在线程池中执行,onPostExecute在主线程中执行,从而完成了从线程池到主线程的切换
下载文件并显示下载进度
public class DownloadTask extends AsyncTask<Void,Integer,Boolean> {
@Override
protected void onPreExecute() {
progressDialog.show(); //显示进度对话框
}
@Override
protected Boolean doInBackground(Void... params) {
while (true){
int downloadPercent = doDownload();
publishProgress(downloadPercent);
if(downloadPercent>=100){
break;
}
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
//更新下载进度
progressDialog.setMessage("Download"+values[0]+"%");
}
@Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss(); //关闭进度对话框
if(result){
Toast.makeText(context,"Download succeeded",Toast.LENGTH_SHORT)
.show();
}else {
Toast.makeText(context,"Download failed",Toast.LENGTH_SHORT).sh
ow();
}
}
}
注意事项:
1.AsyncTask是串行执行任务的,若要并行执行任务,需要调用它的executeOnExecutor方法
2.AsyncTask的类必须在主线程加载,对象必须在主线程创建,execute必须在主线程中调用,一个AsyncTask对象只能执行一次,即只能调用一次execute方法
工作原理:
public final AsyncTask<Params, Progress, Result> execute(Params... params){
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> 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首先会调用其execute方法,而execute又会调executeOnExecutor方法,其中sDefaultExecutor是一个串行的线程池;在AsyncTask中onPreExecute方法先执行,然后此线程池开始执行
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
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);
}
}
}
首先会把AsyncTask的Params参数封装成FutureTask对象,关于FutureTask详细使用可以查看Java并发编程:Callable、Future和FutureTask,在这里它充当Runnable,然后把Future插入到ArrayDeque<Runnable>
队列中,如果此时没有正在执行的任务,则调用scheduleNext方法,此方法会在队列中取出一个Runnable,然后再线程池中执行。
public AsyncTask() {
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
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
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);
}
}
};
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
在线程池中执行取出的Runnable时会调用FutureTask的run方法,此方法会调用mWorker的call方法,因此mWorker的call方法会在线程池中执行。在该方法中首先执行doBackground方法,然后将其返回值传递给postResult方法。
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
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;
}
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
postResult方法通过sHandler发送一个MESSAGE_POST_RESULT消息,这个sHandler是一个静态对象,为了能够切换到主线程,这就要求sHandler必须在主线程中创建。sHandler收到消息后会执行finish方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
如果取消任务就调用onCancelled方法,否则就调用onPostExecute方法。
AnsyncTask中有两个线程池:SerialExecutor用于任务排队、THREAD_POOL_EXECUTOR用于真正的执行任务:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =new LinkedBlockingQueue<Runnable>(128);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
不过不建议使用AsyncTask,因为4.x系统中AsyncTask是串行的,高并发的Task让AsyncTask一个一个串行执行,程序就会很慢。可以看看这篇译文讲解具体原因:译文:Android中糟糕的AsyncTask