参考:https://www.jianshu.com/p/ee1342fcf5e7 https://www.jianshu.com/p/37502bbbb25a
https://www.cnblogs.com/dirt2/p/10473457.html
https://www.cnblogs.com/yanyojun/p/6414919.html
https://blog.csdn.net/weixin_43507738/article/details/83418989
AsyncTask作为官方封装好的轻量级处理异步任务的抽象类,AsyncTask内部封装好Handler和Thread,简化异步线程和UI线程(主线程)之间的通讯操作。
1,AsyncTask的使用,AsyncTask是抽象类,使用它需要实现子类继承它。
//源码
public abstract class AsyncTask<Params, Progress, Result> {
...
}
//子类继承
private static class MyTask extends AsyncTask<String, Integer, String> {
...
}
关于内存泄露问题:
private class MyTask extends AsyncTask<String, Integer, String> {
//执行线程任务前的操作
@Override
protected void onPreExecute() {
super.onPreExecute();
txtHint.setText("准备工作");
}
//线程内部耗时操作
@Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(1000);
txtHint.setText("开始工作");
for(int i =0; i < 100; i++) {
Thread.sleep(100);
publishProgress(i);
}
} catch (Exception e) {
Log.e("MyTask", "error:" + e.getMessage());
}
return "耗时操作完毕";
}
//线程进度回调,显示任务进度
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
txtHint.setText("进度="+ values[0]);
}
//执行任务结果
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("MyTask", s);
txtHint.setText("操作完成");
}
//取消异步操作
@Override
protected void onCancelled() {
super.onCancelled();
txtHint.setText("操作取消");
}
}
按照如上代码创建的MyTask,android studio会提示你:This AsyncTask class should be static or leaks might occur,意思就是建议把MyTask改为静态内部类,否则可能会产生内存泄露。
原因:当AsyncTask在Activity中被声明为非静态内部类时,会持有当前Activity的引用,当Activity需要被销毁时,会因AsyncTask持有对Activity的引用而无法正常被回收,最终可能导致内存泄露。建议方法有两个:
(1)将AsyncTask实现类声明为静态内部类,如:private static class MyTask extends AsyncTask<String, Integer, String>
(2)在Activity的onDestory方法中调用AsyncTask.cancel(true)取消异步任务。
参数说明:
Params:开始异步任务执行时传入的参数类型,对应excute()中传递的参数
Progress:异步任务执行过程中,返回下载进度值的类型
Result:异步任务执行完成后,返回的结果类型,与doInBackground()的返回值类型保持一致
这3个泛型参数使用时不是所有参数都被赋予具体参数类型,若无需使用时可以用Void替代。如class MyTask extends AsyncTask<String, Void, String>。
2,方法说明:
doInBackground:必须重写,异步执行后台线程要完成的任务,耗时操作将在此方法中完成.
onPreExecute:执行后台耗时操作前被调用,通常用于进行初始化操作.
onPostExecute:当doInBackground方法完成后,系统将自动调用此方法,并将doInBackground方法返回的值传入此方法.通过此方法进行UI的更新.
onProgressUpdate:当在doInBackground方法中调用publishProgress方法更新任务执行进度后,将调用此方法.通过此方法我们可以知晓任务的完成进度.
onCancelled:当调用cancle(true/false)这个方法,如果值是true,系统会尝试打断doInBackground方法里的耗时操作,调用这个方法会间接调用 iscancelled() 并且返回true,当doInBackground方法结束后,不再回调onPostExecute而是回调onCancelled方法,为了更快取消任务,在doInBackground方法里周期性执行iscancelled()判断是否需要取消任务。
3,源码分析:
(1)构造方法源码:
public AsyncTask(@Nullable Looper callbackLooper) {
//创建供全局使用的Handler
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
//WorkerRunnable类似于Runnable,WorkerRunnable的call中执行异步操作
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
//设置线程调用标识为true
mTaskInvoked.set(true);
Result result = null;
try {
//设置线程的优先级
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//执行doInBackground异步耗时操作
result = doInBackground(mParams);
//用户线程进入阻塞前跟主线程发送消息,防止用户线程长时间持有调用对象
Binder.flushPendingCommands();
} catch (Throwable tr) {
//运行异常,设置取消的标志
mCancelled.set(true);
throw tr;
} finally {
//把异步操作结果通过mHandler发送到主线程处理
postResult(result);
}
return result;
}
};
//FutureTask监听异步耗时操作完成或取消的状态,将mWorker传入
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
//在执行完任务后检查,将没被调用的Result也一并发出
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) {
//异常发送null
postResultIfNotInvoked(null);
}
}
};
}
private void postResultIfNotInvoked()(Result result) {
// 取得任务标记
final boolean wasTaskInvoked = mTaskInvoked.get();
//如果任务未被执行,将结果通过Handler传递到主线程
if (!wasTaskInvoked) {
postResult(result);
}
}
在构造方法里创建一个WorkerRunnable对象,进行异步耗时操作处理doInBackground方法;FutureTask对象监听WorkerRunnable对象的耗时操作情况,将对应结果传递给主线程。
(2)execute方法源码:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@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;
//执行mFuture的run方法
exec.execute(mFuture);
return this;
}
//exec.execute对应的sDefaultExecutor是一个序列任务执行器,具体创建如下
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//SerialExecutor源码
private static class SerialExecutor implements Executor {
//不安全双向线程队列实现可变数组,没有容量限制
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
//通过synchronized修饰execute方法,确保AsyncTask中的任务串行执行
//多个任务需一个个加到该队列中;然后 执行完队列头部的再执行下一个,以此类推
public synchronized void execute(final Runnable r) {
//FutrueTask对象通过offer方法添加到mTasks末端
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);
}
}
}
THREAD_POOL_EXECUTOR创建和使用,源码:
private static final int CORE_POOL_SIZE = 1;//线程池核心线程长度
private static final int MAXIMUM_POOL_SIZE = 20;//线程池线程最大长度
private static final int BACKUP_POOL_SIZE = 5;//线程池备份长度
private static final int KEEP_ALIVE_SECONDS = 3;//线程保活时间
//线程工厂
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());
}
};
// Used only for rejected executions.
// Initialization protected by sRunOnSerialPolicy lock.
//仅用于被拒绝的执行操作,以锁的机制在具体的拒绝策略里初始化
//用于拒绝策略里的线程池
private static ThreadPoolExecutor sBackupExecutor;
//用于拒绝策略里的链表阻塞队列
private static LinkedBlockingQueue<Runnable> sBackupExecutorQueue;
//拒绝策略处理器
private static final RejectedExecutionHandler sRunOnSerialPolicy =
new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
android.util.Log.w(LOG_TAG, "Exceeded ThreadPoolExecutor pool size");
// As a last ditch fallback, run it on an executor with an unbounded queue.
// Create this executor lazily, hopefully almost never.
//作为最后的退路,在含有不限制长度的队列的执行器里运行
//消极创建这个执行器,最好是不要用的这个执行器
synchronized (this) {
//在锁机制里创建队列和线程池
if (sBackupExecutor == null) {
sBackupExecutorQueue = new LinkedBlockingQueue<Runnable>();
sBackupExecutor = new ThreadPoolExecutor(
BACKUP_POOL_SIZE, BACKUP_POOL_SIZE, KEEP_ALIVE_SECONDS,
TimeUnit.SECONDS, sBackupExecutorQueue, sThreadFactory);
//线程池设置为核心线程在线程保活时间已到时也可以被销毁
sBackupExecutor.allowCoreThreadTimeOut(true);
}
}
sBackupExecutor.execute(r);//最后还是把runnable执行了
}
};
public static final Executor THREAD_POOL_EXECUTOR;
//在静态代码块里创建执行FutureTask任务的线程池,并设置拒绝策略
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), sThreadFactory);
threadPoolExecutor.setRejectedExecutionHandler(sRunOnSerialPolicy);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
实际传递消息的InternalHandler类源码:
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:
//通过finish方法让Handler传递消息给主线程
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//Handler通知主线程更新进度
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
//
private void finish(Result result) {
//如果调用了cancel方法,则执行onCancelled里面的操作
if (isCancelled()) {
onCancelled(result);
} else {
//执行onPostExecute方法里的代码
onPostExecute(result);
}
//将状态设置为FINISHED
mStatus = Status.FINISHED;
}
总结execute方法的流程:
AsyncTask里创建了一个包含拒绝策略的线程池THREAD_POOL_EXECUTOR,用来执行异步耗时操作,当调用execute方法时,实际是执行executeOnExecutor方法,判断状态,正常则设置当前状态为RUNNING,同时回调onPreExecute方法,接着通过SerialExecutor对象执行execute方法,将FutureTask对象插入到到一个双向线程队列里等待被执行,调用scheduleNext方法,线程池THREAD_POOL_EXECUTOR执行FutureTask对象里的方法,FutureTask包含WorkerRunnable对象,此时执行doInBackground方法,再调用postResult(result)方法通过InternalHandler类将消息传给主线程,然后在finish方法里通过MESSAGE_POST_RESULT标识判断是否调用了cancel方法取消操作,从而执行onCancelled或onPostExecute回调方法。
这篇文章分析的比较好:https://www.jianshu.com/p/37502bbbb25a
(3)publishProgress方法源码:
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
当doInBackground运行过程中,需要更新当前进度信息,调用publishProgress方法,InternalHandler类发送一个MESSAGE_POST_PROGRESS的消息,回调onProgressUpdate(Progress... values)方法。
(4)cancel方法源码:
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
//FutureTask的cancel方法
public boolean cancel(boolean mayInterruptIfRunning) {
//判断不符合打断条件的直接return
if (!(state == NEW &&
U.compareAndSwapInt(this, STATE, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
//如果值为true,强制打断线程,此时容易抛出异常
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
U.putOrderedInt(this, STATE, INTERRUPTED);
}
}
} finally {
//删除所有等待的线程并发出信号,调用done方法,并将可调用的线程置空
finishCompletion();
}
return true;
}
调用cancel方法会调用FutureTask的cancel方法,如果传入的值为true则强制打断线程此时容易抛出异常。最终删除所有等待的线程并置空,发出信号调用done方法。
4,使用注意事项:
AsyncTask的execute方法只能被调用一次,多次调用闪退,提示Cannot execute task: the task is already running
在targetSdkVersion 29的版本里可以在子线程里执行AsyncTask,5.0以下低版本不能这么做,但还是建议在主线程里创建AsyncTask。
AsyncTask被重写的方法尽量不要手动调用。
5,优缺点分析:参考:https://blog.csdn.net/weixin_43507738/article/details/83418989
(1)优点:AsyncTask封装了Handler和Thread(线程池)给用户使用,用户不用管里面的具体实现,只需继承和重写对应的方法。
(2)缺点:
<1>旋转屏幕等造成的结果处理问题:当Activity因旋转屏幕而被销毁重建时,AsyncTask持有的是对屏幕没有旋转前的Activity的引用,此时onPostExecute对重建后的Activity没有实际意义。建议保留对AsyncTask的引用,在Activity重启时重启AsyncTask任务。
<2>生命周期:Activity的生命周期和AsyncTask的生命周期不同步,往往Activity已经被销毁,AsyncTask还在运行,此时容易造成内存泄露。所以需要在合适实际调用cancel方法手动取消任务。