1.AsyncTask
- AsyncTask是一种轻量级的异步任务类,它可以在线程池中执行后台任务,然后把执行的进度和最终结果传递给主线程并在主线程中更新UI。AsyncTask可以更加方便地执行后台任务以及在主线程中访问UI。但是并不适合进行特别耗时的后台任务,如果需要建议用线程池。
//可以看到它是一个抽象泛型类,提供了Params、Progress和Result这三个泛型参数
//Params:参数类型
//Progress:后台任务的执行进度类型
//Result:表示后台任务的返回结果的类型
//如果不需要传递具体的参数,三个泛型参数可以用Void来替换
public abstract class AsyncTask<Params, Progress, Result>
/**
* Runs on the UI thread before {@link #doInBackground}.
* 一般可以用于做一些准备操作
* @see #onPostExecute
* @see #doInBackground
*/
@MainThread
protected void onPreExecute() {
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
* 在线程池中执行,此方法用于执行异步任务,参数代表异步任务输入参数。再次方法中可以通过publishProgress方法来更新任务的进度,
publishProgress方法会调用onProgressUpdate方法,需要返回计算结果给onPostExecute方法
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@WorkerThread
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread after {@link #publishProgress} is invoked.
* The specified values are the values passed to {@link #publishProgress}.
*
* @param values The values indicating progress.
* 在主线程中执行,当后台任务的执行进度发生改变时此方法会被调用
* @see #publishProgress
* @see #doInBackground
*/
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onProgressUpdate(Progress... values) {
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
* 在主线程中执行,在异步任务执行之后,此方法会被调用,其中result参数是后台任务的返回值,即doInBackground的返回值
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
一个串性线程池,一个进程中所有的AsyncTask全部在这个线程池中排队执行
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();