基本用法
AsyncTask是一個(gè)抽象類憎兽,所以如果我們想使用它码俩,就必須要?jiǎng)?chuàng)建一個(gè)子類去繼承它书聚。在繼承時(shí)我們可以為AsyncTask類指定三個(gè)泛型參數(shù)腺办,這三個(gè)參數(shù)的用途如下:
定義:public abstract class AsyncTask<Params, Progress, Result> {}
- Params
在執(zhí)行AsyncTask時(shí)需要傳入的參數(shù)抹锄,可用于在后臺(tái)任務(wù)中使用逆瑞。
- Progress
后臺(tái)任務(wù)執(zhí)行時(shí),如果需要在界面上顯示當(dāng)前的進(jìn)度伙单,則使用這里指定的泛型作為進(jìn)度單位获高。 - Result
當(dāng)任務(wù)執(zhí)行完畢后,如果需要對(duì)結(jié)果進(jìn)行返回吻育,則使用這里指定的泛型作為返回值類型谋减。
常使用的方法
- void onPreExecute() {}
運(yùn)行在ui線程,準(zhǔn)備工作 - Result doInBackground(Params... params);
在此方法所有代碼都會(huì)在子線程中運(yùn)行扫沼,可通過(guò) publishProgress 來(lái)更新進(jìn)度出爹。它會(huì)調(diào)用 onProgressUpdate方法。 - void onProgressUpdate(Progress... values) {}
運(yùn)行在ui線程 - void onPostExecute(Result result) {}
運(yùn)行在ui線程
示例(來(lái)自AsyncTask類說(shuō)明)
private class DownloadFilesTask extends AsyncTask <URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
這樣調(diào)用即可:new DownloadFilesTask().execute (url1,url2,url3);
分析AsyncTask的源碼
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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.
*/
package android.os;
import java.util.ArrayDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
//獲取當(dāng)前的cpu核心數(shù)
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//線程池核心容量
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//線程池最大容量
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//過(guò)剩的空閑線程的存活時(shí)間
private static final int KEEP_ALIVE = 1;
//ThreadFactory 線程工廠缎除,通過(guò)工廠方法newThread來(lái)獲取新線程
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
//原子整數(shù)严就,可以在超高并發(fā)下正常工作
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
//靜態(tài)阻塞式隊(duì)列,用來(lái)存放待執(zhí)行的任務(wù)器罐,初始容量:128個(gè)
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* 靜態(tài)并發(fā)線程池梢为,可以用來(lái)并行執(zhí)行任務(wù),盡管從3.0開(kāi)始轰坊,AsyncTask默認(rèn)是串行執(zhí)行任務(wù)
* 但是我們?nèi)匀荒軜?gòu)造出并行的AsyncTask
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
* 靜態(tài)串行任務(wù)執(zhí)行器铸董,其內(nèi)部實(shí)現(xiàn)了串行控制,
* 循環(huán)的取出一個(gè)個(gè)任務(wù)交給上述的并發(fā)線程池去執(zhí)行
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//消息類型:發(fā)送結(jié)果
private static final int MESSAGE_POST_RESULT = 0x1;
//消息類型:更新進(jìn)度
private static final int MESSAGE_POST_PROGRESS = 0x2;
/**靜態(tài)Handler肴沫,用來(lái)發(fā)送上述兩種通知粟害,采用UI線程的Looper來(lái)處理消息
* 這就是為什么AsyncTask必須在UI線程調(diào)用,因?yàn)樽泳€程
* 默認(rèn)沒(méi)有Looper無(wú)法創(chuàng)建下面的Handler颤芬,程序會(huì)直接Crash
*/
private static final InternalHandler sHandler = new InternalHandler();
//默認(rèn)任務(wù)執(zhí)行器悲幅,被賦值為串行任務(wù)執(zhí)行器套鹅,就是它,AsyncTask變成串行的了
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//如下兩個(gè)變量我們先不要深究汰具,不影響我們對(duì)整體邏輯的理解
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
//任務(wù)的狀態(tài) 默認(rèn)為掛起卓鹿,即等待執(zhí)行,其類型標(biāo)識(shí)為易變的(volatile)
private volatile Status mStatus = Status.PENDING;
//原子布爾型留荔,支持高并發(fā)訪問(wèn)吟孙,標(biāo)識(shí)任務(wù)是否被取消
private final AtomicBoolean mCancelled = new AtomicBoolean();
//原子布爾型,支持高并發(fā)訪問(wèn)聚蝶,標(biāo)識(shí)任務(wù)是否被執(zhí)行過(guò)
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
/*串行執(zhí)行器的實(shí)現(xiàn)拔疚,我們要好好看看,它是怎么把并行轉(zhuǎn)為串行的
*目前我們需要知道既荚,asyncTask.execute(Params ...)實(shí)際上會(huì)調(diào)用
*SerialExecutor的execute方法,這一點(diǎn)后面再說(shuō)明栋艳。也就是說(shuō):當(dāng)你的asyncTask執(zhí)行的時(shí)候恰聘,
*首先你的task會(huì)被加入到任務(wù)隊(duì)列,然后排隊(duì)吸占,一個(gè)個(gè)執(zhí)行
*/
private static class SerialExecutor implements Executor {
//線性雙向隊(duì)列晴叨,用來(lái)存儲(chǔ)所有的AsyncTask任務(wù)
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//當(dāng)前正在執(zhí)行的AsyncTask任務(wù)
Runnable mActive;
public synchronized void execute(final Runnable r) {
//將新的AsyncTask任務(wù)加入到雙向隊(duì)列中
mTasks.offer(new Runnable() {
public void run() {
try {
//執(zhí)行AsyncTask任務(wù)
r.run();
} finally {
//當(dāng)前AsyncTask任務(wù)執(zhí)行完畢后,進(jìn)行下一輪執(zhí)行矾屯,如果還有未執(zhí)行任務(wù)的話
//這一點(diǎn)很明顯體現(xiàn)了AsyncTask是串行執(zhí)行任務(wù)的兼蕊,總是一個(gè)任務(wù)執(zhí)行完畢才會(huì)執(zhí)行下一個(gè)任務(wù)
scheduleNext();
}
}
});
//如果當(dāng)前沒(méi)有任務(wù)在執(zhí)行,直接進(jìn)入執(zhí)行邏輯
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//從任務(wù)隊(duì)列中取出隊(duì)列頭部的任務(wù)件蚕,如果有就交給并發(fā)線程池去執(zhí)行
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* 任務(wù)的三種狀態(tài)
*/
public enum Status {
/**
* 任務(wù)等待執(zhí)行
*/
PENDING,
/**
* 任務(wù)正在執(zhí)行
*/
RUNNING,
/**
* 任務(wù)已經(jīng)執(zhí)行結(jié)束
*/
FINISHED,
}
/** 隱藏API:在UI線程中調(diào)用孙技,用來(lái)初始化Handler */
public static void init() {
sHandler.getLooper();
}
/** 隱藏API:為AsyncTask設(shè)置默認(rèn)執(zhí)行器 */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
//doInBackground執(zhí)行完畢,發(fā)送消息
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
/**
* 返回任務(wù)的狀態(tài)
*/
public final Status getStatus() {
return mStatus;
}
/**
* 這個(gè)方法是我們必須要重寫(xiě)的排作,用來(lái)做后臺(tái)計(jì)算
* 所在線程:后臺(tái)線程
*/
protected abstract Result doInBackground(Params... params);
/**
* 在doInBackground之前調(diào)用牵啦,用來(lái)做初始化工作
* 所在線程:UI線程
*/
protected void onPreExecute() {
}
/**
* 在doInBackground之后調(diào)用,用來(lái)接受后臺(tái)計(jì)算結(jié)果更新UI
* 所在線程:UI線程
*/
protected void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress} is invoked.
/**
* 在publishProgress之后調(diào)用妄痪,用來(lái)更新計(jì)算進(jìn)度
* 所在線程:UI線程
*/
protected void onProgressUpdate(Progress... values) {
}
/**
* cancel被調(diào)用并且doInBackground執(zhí)行結(jié)束哈雏,會(huì)調(diào)用onCancelled,表示任務(wù)被取消
* 這個(gè)時(shí)候onPostExecute不會(huì)再被調(diào)用衫生,二者是互斥的裳瘪,分別表示任務(wù)取消和任務(wù)執(zhí)行完成
* 所在線程:UI線程
*/
@SuppressWarnings({"UnusedParameters"})
protected void onCancelled(Result result) {
onCancelled();
}
protected void onCancelled() {
}
public final boolean isCancelled() {
return mCancelled.get();
}
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* 這個(gè)方法如何執(zhí)行和系統(tǒng)版本有關(guān),在AsyncTask的使用規(guī)則里已經(jīng)說(shuō)明罪针,如果你真的想使用并行AsyncTask彭羹,
* 也是可以的,只要稍作修改
* 必須在UI線程調(diào)用此方法
*/
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
//串行執(zhí)行
return executeOnExecutor(sDefaultExecutor, params);
//如果我們想并行執(zhí)行泪酱,這樣改就行了皆怕,當(dāng)然這個(gè)方法我們沒(méi)法改
//return executeOnExecutor(THREAD_POOL_EXECUTOR, params);
}
/**
* 通過(guò)這個(gè)方法我們可以自定義AsyncTask的執(zhí)行方式毅舆,串行or并行,甚至可以采用自己的Executor
* 為了實(shí)現(xiàn)并行愈腾,我們可以在外部這么用AsyncTask:
* asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Params... params);
* 必須在UI線程調(diào)用此方法
*/
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會(huì)最先執(zhí)行
onPreExecute();
mWorker.mParams = params;
//然后后臺(tái)計(jì)算#doInBackground才真正開(kāi)始
exec.execute(mFuture);
//接著會(huì)有#onProgressUpdate被調(diào)用憋活,最后是#onPostExecute
return this;
}
/**
* 這是AsyncTask提供的一個(gè)靜態(tài)方法,方便我們直接執(zhí)行一個(gè)runnable
*/
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
/**
* 打印后臺(tái)計(jì)算進(jìn)度虱黄,onProgressUpdate會(huì)被調(diào)用
*/
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
//任務(wù)結(jié)束的時(shí)候會(huì)進(jìn)行判斷悦即,如果任務(wù)沒(méi)有被取消,則onPostExecute會(huì)被調(diào)用
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
//AsyncTask內(nèi)部Handler橱乱,用來(lái)發(fā)送后臺(tái)計(jì)算進(jìn)度更新消息和計(jì)算完成消息
private static class InternalHandler extends Handler {
@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 static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
在3.0版本中AsyncTask的改動(dòng)還是挺大的辜梳,在3.0之前的AsyncTask可以同時(shí)有5個(gè)任務(wù)在執(zhí)行,而3.0之后的AsyncTask同時(shí)只能有1個(gè)任務(wù)在執(zhí)行泳叠。為什么升級(jí)之后可以同時(shí)執(zhí)行的任務(wù)數(shù)反而變少了呢作瞄?這是因?yàn)楦潞蟮腁syncTask已變得更加靈活,如果不想使用默認(rèn)的線程池危纫,還可以自由地進(jìn)行配置宗挥。比如使用如下的代碼來(lái)啟動(dòng)任務(wù):
Executor exec = new ThreadPoolExecutor(15, 200, 10,
TimeUnit.SECONDS, new LinkedBlockingQueue());
new DownloadTask().executeOnExecutor(exec);