前言:前面看到Handler、HandlerThread、IntentService都与异步任务有关,这让我联系到了AsyncTask,这也是很有名的可以执行异步任务的类,Android已经帮我们封装好了准备、执行、状态更新以及提交结果的接口。
1. AsyncTask使用
很多例子都是用进度条来演示的,我自己也照着写了一个,先温习一下基本的使用方法。
布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.asynctasktest.MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="257dp"
android:layout_height="7dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
activity:
package com.example.asynctasktest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
TextView txView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
txView = findViewById(R.id.textView);
new Task.execute((Object)null);
}
class Task extends AsyncTask<Object,Integer,Object>{
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
txView.setText("end");
}
@Override
protected Object doInBackground(Object[] objects) {
for(int i = 0; i <= 100; i++){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return null;
}
@Override
protected void onProgressUpdate(Integer[] values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
txView.setText(values[0] + "%");
}
@Override
protected void onPreExecute() {
super.onPreExecute();
txView.setText("begin");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. 分析AsyncTask的使用
由于AsyncTask是个抽象类,所以我们继承它的实现必须实现它的抽象方法,至于后面的泛型先不管
public abstract class AsyncTask<Params, Progress, Result> {
它的抽象方法只有一个:
/**
* 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.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@WorkerThread
protected abstract Result doInBackground(Params... params);
从注释来看我们知道以下几点:
1) doInBackground是让子线程执行对于任务的方法。
2) 在doInBackground中可以调用publishProgress在UI线程中更新进度
3)入参是新建任务的时候传递进来的,指的就是“params”是在new AsyncTask的时候传进来的。
其实如果我们执行的方法和UI线程没有交互的话,实现doInBackground就满足要求了。
如上注释还提及了几个重要的方法:
- onPreExecute
- onProgressUpdate
- onPostExecute
在这里贴一下这三个方法的源码
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
@MainThread
protected void onPreExecute() {
}
/**
* <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}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
/**
* 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) {
}
从上面的注释可以看出
1) onPreExecute是在doInBackground之前执行的,相当于做准备工作
2) onPostExecute接收来自doInBackground传递来的参数在UI线程进行结果的处理
3)onProgressUpdate 在调用publishProgress后会被调用到,参数就是publishProgress传递来的
梳理下方法的执行顺序:
onPreExecute---doInBackground(---publishProgress---onProgressUpdate)---onPostExecute
这里再将AsyncTask和它的重要方法放一起理解一下它的泛型参数
public abstract class AsyncTask<Params, Progress, Result> {
protected abstract Result doInBackground(Params... params);
protected void onProgressUpdate(Progress... values) {
}
protected void onPostExecute(Result result) {
}
- Params其实是doInBackground接受参数的类型
- Progress是更新的进度条的类型
- Result既是doInBackground的返回值类型又是onPostExecute的参数类型
如果写好了AsyncTask,那就直接调用就好了,调用方法很简单。
new Task().execute((Object)null);
execute()对应源码如下所示:
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>Note: this function schedules the task on a queue for a single background
* thread or pool of threads depending on the platform version. When first
* introduced, AsyncTasks were executed serially on a single background thread.
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
* executed on a single thread to avoid common application errors caused
* by parallel execution. If you truly want parallel execution, you can use
* the {@link #executeOnExecutor} version of this method
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
* on its use.
*
* <p>This method must be invoked on the UI thread.
*
* @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 #executeOnExecutor(java.util.concurrent.Executor, Object[])
* @see #execute(Runnable)
*/
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
看注释发现了了不得的东西,AsncTask在Android D的时候是用的线程池,而不是用的单线程执行doInBackground的任务的。
在Android H的时候又换成单线程了,估计由于历史原因,executeOnExecutor保留了下来。
主要的流程梳理完了,这里正好可以顺着execute的源码往下看了。
3. 源码分析
刚才看到execute方法调用到executeOnExecutor里面了,传入了一个默认的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);
}
}
}
emmmm,这边其实自己维持了一个队列,新来一个任务放在结尾,当工作任务即mActive为空的时候,从队列开头取出一个任务给线程池来完成,现在先往下看了。
/**
* 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:
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不能在被调用了还没完成再调用,也不能在调用完成后继续调用,是一次性的;继而调用了onPreExecute()来完成准备工作,这里补一下AsyncTask的构造方法,mWorker和mFuture就是在那里面初始化的。
/**
* 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);
}
}
};
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
虽然上面的两个类都不熟悉,但是流程大致看到了,doInBackground后再调用postResult提交执行的结果,这和之前分析的流程一致。
至于进度条更新和结果更新相关代码如下:
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:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will not be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
可以看到是内部新建了一个handler用于消息的传递,分别处理进度条的更新和结果的更新。
结果的更新稍微特殊点,如果AsyncTask被取消了,则不会执行onPostExecute了。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
我们实现AsyncTask的时候最好再实现一个如下方法进行方法取消后的UI线程处理。
/**
* <p>Applications should preferably override {@link #onCancelled(Object)}.
* This method is invoked by the default implementation of
* {@link #onCancelled(Object)}.</p>
*
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* @see #onCancelled(Object)
* @see #cancel(boolean)
* @see #isCancelled()
*/
@MainThread
protected void onCancelled() {
}
源码分析流程有模糊的地方主要是由于FutureTask和Executor不熟悉,简单看下这两个类的作用。
Future:FureTask参考
Executor:作为灵活且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务的线程相当于消费者,并用Runnable来表示任务,Executor的实现还提供了对生命周期的支持,以及统计信息收集,应用程序管理机制和性能监视等机制。
在看源码过程中发现默认的线程池是如下定义:
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;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
说明默认线程池是最大cpu数×2-1,核心线程数2-4个,保留活性是30s.
现在手机一般是8核,所以线程池一般是大小15,core pool size是4个。
这个线程池注意是static的,也就是说某个程序只要用的AsyncTask了,那么执行的异步任务都在这个大小15的线程池里跑,但是如果同时调用两个asyncTask完成异步任务,这会阻塞住一个(SerialExecutor造成的),不想受其他程序影响可以自己创建个线程池。
我自己在原来程序里加了些log,发现AsyncTask多次执行是串行实现的,和之前分析的一模一样。
new Task().execute(1);
new Task().execute(2);
new Task().execute(3);
02-10 17:30:59.675 22003-22003/com.example.asynctasktest D/asyncTest: begin
02-10 17:30:59.676 22003-22003/com.example.asynctasktest D/asyncTest: begin
02-10 17:30:59.676 22003-22003/com.example.asynctasktest D/asyncTest: begin
02-10 17:30:59.678 22003-22078/com.example.asynctasktest D/asyncTest: 1
02-10 17:31:20.092 22003-22714/com.example.asynctasktest D/asyncTest: 2
02-10 17:31:20.112 22003-22003/com.example.asynctasktest D/asyncTest: end
02-10 17:31:40.404 22003-22720/com.example.asynctasktest D/asyncTest: 3
02-10 17:31:40.410 22003-22003/com.example.asynctasktest D/asyncTest: end
02-10 17:32:00.728 22003-22003/com.example.asynctasktest D/asyncTest: end
之前我还想static是某个应用共享的,还是进程共享的,我试了下
应用间static的变量是不共享的:
02-10 17:46:52.274 27250-27269/com.example.asynctasktest D/asyncTest: begin
02-10 17:46:52.274 27250-27269/com.example.asynctasktest D/asyncTest: 1
02-10 17:46:53.735 27281-27300/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:46:53.735 27281-27300/com.example.asynctasktest2222 D/asyncTest: 1
02-10 17:47:12.555 27250-27269/com.example.asynctasktest D/asyncTest: end
02-10 17:47:12.557 27250-27320/com.example.asynctasktest D/asyncTest: begin
02-10 17:47:12.557 27250-27320/com.example.asynctasktest D/asyncTest: 2
02-10 17:47:14.026 27281-27300/com.example.asynctasktest2222 D/asyncTest: end
02-10 17:47:14.027 27281-27321/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:47:14.028 27281-27321/com.example.asynctasktest2222 D/asyncTest: 2
02-10 17:47:32.829 27250-27320/com.example.asynctasktest D/asyncTest: end
02-10 17:47:32.831 27250-27326/com.example.asynctasktest D/asyncTest: begin
02-10 17:47:32.831 27250-27326/com.example.asynctasktest D/asyncTest: 3
02-10 17:47:34.337 27281-27321/com.example.asynctasktest2222 D/asyncTest: end
02-10 17:47:34.339 27281-27327/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:47:34.339 27281-27327/com.example.asynctasktest2222 D/asyncTest: 3
02-10 17:47:53.097 27250-27326/com.example.asynctasktest D/asyncTest: end
02-10 17:47:54.658 27281-27327/com.example.asynctasktest2222 D/asyncTest: end
那activity间static的变量是否共享呢?试了下activity间是共享的,进程间是共享的,或者说应用内部是共享的。
02-10 17:57:04.016 31010-31080/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:57:04.016 31010-31080/com.example.asynctasktest2222 D/asyncTest: 1
02-10 17:57:24.307 31010-31080/com.example.asynctasktest2222 D/asyncTest: end
02-10 17:57:24.310 31010-31538/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:57:24.310 31010-31538/com.example.asynctasktest2222 D/asyncTest: 2
02-10 17:57:44.573 31010-31538/com.example.asynctasktest2222 D/asyncTest: end
02-10 17:57:44.575 31010-31546/com.example.asynctasktest2222 D/asyncTest: begin
02-10 17:57:44.575 31010-31546/com.example.asynctasktest2222 D/asyncTest: 3
02-10 17:58:04.857 31010-31546/com.example.asynctasktest2222 D/asyncTest: end
02-10 17:58:04.859 31010-31664/com.example.asynctasktest2222 D/asyncTest2: begin
02-10 17:58:04.859 31010-31664/com.example.asynctasktest2222 D/asyncTest2: 1
02-10 17:58:25.168 31010-31664/com.example.asynctasktest2222 D/asyncTest2: end
02-10 17:58:25.170 31010-31676/com.example.asynctasktest2222 D/asyncTest2: begin
02-10 17:58:25.171 31010-31676/com.example.asynctasktest2222 D/asyncTest2: 2
02-10 17:58:45.487 31010-31676/com.example.asynctasktest2222 D/asyncTest2: end
02-10 17:58:45.488 31010-31682/com.example.asynctasktest2222 D/asyncTest2: begin
02-10 17:58:45.488 31010-31682/com.example.asynctasktest2222 D/asyncTest2: 3
02-10 17:59:05.799 31010-31682/com.example.asynctasktest2222 D/asyncTest2: end
4.总结
AsyncTask主要分为两部分工作,一部分是在UI线程完成的,主要有onPreExecute/onPublishProgress/onPostExecute;
一部分是在线程池完成的,默认实现是和自己进程下所有页面共同享有一个线程池的使用,主要有doInBackground。很好的将UI更新和任务分割开来,简化了平常工作中遇到的耗时操作和UI更新的难题。
写的有点乱,后面学习了FutureTask/Executor/Callable后再回来重写一下。