一、使用方法
AsyncTask通常用于實現在后臺線程中完成耗時操作,然后在主線程中更新UI。
繼承AsyncTask需要指定3個泛型參數:
AsyncTask<Params, Progress, Result>
- Params: 啟動任務執行的輸入參數的類型
- Progress: 后臺任務完成的進度值得類型
- Result: 后臺執行任務完成后返回結果的類型
使用AsyncTask的主要方法:
- protected String doInBackground(Params... params)
在后臺線程池中執行,可以調用publishProgress(Progress... values)方法觸發onProgressUpdate方法,從而更新任務任務進度 - protected void onProgressUpdate(Progress... values)
在UI線程執行,更新進度條等UI - protected void onPreExecute()
在doInBackground方法之前UI線程執行,通常用于完成初始化工作。 - protected void onPostExecute(Result result)
在UI線程執行,在doInBackground方法之后會自動調用,并將doInBackground的返回值傳給該方法。
使用AsyncTask必須遵守以下原則:
- 必須在UI線程創建AsyncTask實例,API26之后不需要
- 必須在UI線程中調用AsyncTask的execute()方法,因為onPreExecute需要在主線程回調
- 每個AsyncTask在后臺任務執行完成前只能被執行一次,多次調用會引發異常
demo
public class MainActivity extends AppCompatActivity {
private TextView show = null;
private Button button = null;
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)findViewById(R.id.show);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
download();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
public void download() throws MalformedURLException {
MyAsyncTask task = new MyAsyncTask(this);
//AsyncTask第一個參數為Void,如果不是Void,execute方法需要傳入參數。
task.execute();
}
class MyAsyncTask extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
int hasRead = 0;
Context mContext;
public MyAsyncTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
try{
while (hasRead < 100) {
hasRead++;
sb.append(hasRead + " ");
publishProgress(hasRead);
Thread.sleep(200);
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(mContext);
pDialog.setTitle("任務正在執行中");
pDialog.setMessage("任務正在執行中, 敬請等待...");
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
show.setText("已經讀取了【" + values[0] + "】行!");
pDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
show.setText(s);
if (hasRead == 100) {
pDialog.dismiss();
}
}
}
}
[圖片上傳失敗...(image-c5125d-1551414183649)]二、AsyncTask源碼分析
首先來看下構造函數
/frameworks/base/core/java/android/os/AsyncTask.java
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
this((Looper) null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Handler handler) {
this(handler != null ? handler.getLooper() : null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
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);
}
}
};
}
構造函數中首先創建了一個WorkerRunnable對象,我們看下WorkerRunnable定義:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
WorkerRunnable繼承自Callable接口,Callable接口跟Runnable接口類似,只是其中的call方法帶返回值
public interface Runnable {
public abstract void run();
}
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
回到AsyncTask構造函數中,在WorkerRunnable的call方法中調用了doInBackground,doInBackground執行完后把結果傳給postResult方法。繼續往下看創建了FutureTask對象,FutureTask可以通過調用ExecutorService.submit執行參數Callable中的任務,也可以用于獲得Callable任務的執行結果、查詢是否完成和取消任務等操作。所以AsyncTask構造函數中主要工作是:
- 在一個Callable對象mWorker的call方法中,調用doInBackground方法,并將結果傳給postResult方法
- 創建以mWorker作為參數的FutureTask對象mFuture。
接下來再看AsyncTask.execute()方法:
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
* allow multiple tasks to run in parallel on a pool of threads managed by
* AsyncTask, however you can also use your own {@link Executor} for custom
* behavior.
*
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
* a thread pool is generally <em>not</em> what one wants, because the order
* of their operation is not defined. For example, if these tasks are used
* to modify any state in common (such as writing a file due to a button click),
* there are no guarantees on the order of the modifications.
* Without careful work it is possible in rare cases for the newer version
* of the data to be over-written by an older one, leading to obscure data
* loss and stability issues. Such changes are best
* executed in serial; to guarantee such work is serialized regardless of
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
*
* <p>This method must be invoked on the UI thread.
*
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
* convenient process-wide thread pool for tasks that are loosely coupled.
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #execute(Object[])
*/
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
//如果任務沒有結束mStatus狀態為RUNNING,則會拋出異常,所以每個AsyncTask在后臺任務執行完成前只能被執行一次,多次調用會引發異常
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;
}
execute() 方法直接調用executeOnExecutor傳入默認的sDefaultExecutor,是串行Executor,executeOnExecutor()方法首先回調onPreExecute(),然后調用sDefaultExecutor.execute()執行構造函數中的Callable任務mWorker,下面看下sDefaultExecutor的定義:
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
//Runnable緩存隊列
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//mActive正在執行的Runnable
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
//mFuture的run()方法會調用mWorker的call()方法
r.run();
} finally {
//執行完一個任務后再從緩存隊列中取下一個
scheduleNext();
}
}
});
//第一次mActive為null,直接調用scheduleNext
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
//真正在線程池中開始執行任務
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
SerialExecutor主要作用請參考注釋,其實SerialExecutor的作用是保證來的線程是串行執行的,真正在后臺開始執行任務是THREAD_POOL_EXECUTOR.execute(mActive)
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());
}
};
//緩存隊列,用來存儲執行的任務,基于鏈表的先進先出隊列,這里指定長度為128
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
//但是如果調用了allowCoreThreadTimeOut(boolean)方法,在線程池中的線程數不大于corePoolSize時,keepAliveTime參數也會起作用,直到線程池中的線程數為0;
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
java.uitl.concurrent.ThreadPoolExecutor類是線程池中最核心的一個類,這里創建ThreadPoolExecutor對象的幾個重要參數:
- CORE_POOL_SIZE
線程池中的核心線程個數,當線程池中線程數小于CORE_POOL_SIZE時,進來新任務就創建線程,當大于CORE_POOL_SIZE時,則放入緩存隊列中,這里定義為2到4個。 - MAXIMUM_POOL_SIZE
線程池中最大線程個數,當緩存隊列已滿或者任務劇增時,最多可以創建的線程個數,這里為 CPU_COUNT * 2 + 1 - KEEP_ALIVE_SECONDS
表示線程沒有任務執行時最多保持多久時間會終止。默認情況下,只有當線程池中的線程數大于corePoolSize時,keepAliveTime才會起作用,直到線程池中的線程數不大于corePoolSize,這里是30s - TimeUnit.SECONDS
keepAliveTime的時間單位為s - sPoolWorkQueue
線程池緩存隊列 - sThreadFactory
線程工廠,用來創建線程
回到前面構造函數中執行完后臺任務doInBackground,會調用postResult處理結果
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
這里getHandler()通常返回InternalHandler的靜態實例sHandler
private static InternalHandler sHandler;
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
//這里回調onPostExecut
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
sHandler綁定的主線程的Looper,這就保證了onProgressUpdate和onPostExecute函數在主線程中回調
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
-
關于串行并行問題
串行:
直接調用execute方法使用默認的Executor: SERIAL_EXECUTOR,這是個靜態實例,所以適用于以下有多個任務的情況下,保證串行執行
MyAsyncTask task1 = new MyAsyncTask(); MyAsyncTask task2 = new MyAsyncTask(); MyAsyncTask task3 = new MyAsyncTask(); ... ... task1.execute(); task2.execute(); task3.execute();
并行:
如果希望并行執行任務則需要調用方法executeOnExecutor(),傳入參數Executor:THREAD_POOL_EXECUTOR
MyAsyncTask task1 = new MyAsyncTask(); MyAsyncTask task2 = new MyAsyncTask(); MyAsyncTask task3 = new MyAsyncTask(); ... ... task1.executeOnExecutor(THREAD_POOL_EXECUTOR,...); task2.executeOnExecutor(THREAD_POOL_EXECUTOR,...); task3.executeOnExecutor(THREAD_POOL_EXECUTOR,...);