Android 实现多任务——AsyncTask(源码解析)

Android 实现多任务——Handler(源码解析)见另一篇文章,在本文中着重分析AsyncTask这个工具类。
用Handler在子线程中更新UI,虽然可以避免在主线程中进行耗时操作,但耗时的操作总会启动一些匿名的子线程,会在一定的程度上带来性能问题,因此Android提供了AsyncTask工具类(异步执行任务),专门用来处理后台比较耗时的任务。

AsyncTask的使用

  1. 创建AsyncTask子类&根据需求实现核心方法;
  2. 创建AsyncTask子类的实例对象;
  3. 手动调用execute()执行异步线程任务。
/**
* params :doInBackground 方法的参数类型
* Progress :AsyncTask 所执行的后台任务的进度类型
* Result :后台任务的返回结果类型
*/
class MemoryCleanAsyncTask extends AsyncTask<Params,Progress,Result>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //此方法会在doInBackground执行前被调用,用于进行一些准备工作
    }

    @Override
    protected String doInBackground(Void... voids) {
        //必须复写
        //后台耗时任务执行中...
        //在该方法中可以调用publishProgress来更新任务进度(publishProgress内部会调用onProgressUpdate方法)
        return null;
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //后台执行的任务会发回一个或多个阶段性进度结果,表示任务进度更新,这个是可以用来更新交互页面。
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //必须复写
        //后台任务执行完毕会调用该方法,返回后台任务执行结果,可用来刷新UI
    }
     @Override
    protected void onCancelled() {
        super.onCancelled();
        //在后台任务被取消时回调
    }
}

//执行AsycnTask
//必须在主线程中加载AsyncTask类,完成sHandler静态成员初始化操作
MemoryCleanAsyncTask mAsyncTack=new MemoryCleanAsyncTask ();
mAsyncTack.execute();

特别需要注意:

  1. 只有doInBackground()由AsyncTask内部线程池执行,其余方法均在主线程中执行;
  2. AsyncTask实例必须在主线程中创建;
  3. execute()方法必须在主线程中调用;
  4. 上述AsyncTask中的方法均不要手动调用,需要在主线程中实例化Task来调用;
  5. 一个AsyncTask对象只能调用一次execute方法,多次调用会出现异常。

1、执行过程是从mAsyncTack.execute()开始进行的,那就从execute()开始

/**
* AsyncTask.java
* sDefaultExecutor:AsyncTask 默认串行执行器(线程池)
* Android 3.0 以后调用execute(),使用的是串行方式来执行后台任务
*/
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

sDefaultExecutor实质是SerialExecutor()对象

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

private static class SerialExecutor implements Executor {
       //mTasks 为SerialExecutor 串行线程池中的任务缓存队列
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        //正在执行的AsyncTask对象
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
           //向任务缓存队列中添加一个任务
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                       //r 为之前传入的mFuture ,相当于调用mFuture.run()
                       //而mFuture的run方法内部会调用mWorker.call(),进而会调用doInBackground()方法,因此后台任务开始执行
                        r.run();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            //mTasks.poll()缓存队列
            if ((mActive = mTasks.poll()) != null) {
                //THREAD_POOL_EXECUTOR 线程池对象
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

Question1:提交到任务缓存队列中的任务何时能够执行?
Answer :在SerialExecutor 类中定义了一个Runnable 变量mActive,代表着当前正在执行的AsyncTask对象。在execute方法中会判断mActive是否为空,若为空调用scheduleNext()方法。在scheduleNext()方法中,若缓存队列非空,则调用 THREAD_POOL_EXECUTOR.execute()方法执行从缓存队列中取出的任务,此时后台任务便开始真正的执行了~

2、调用executeOnExecutor()

 public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
           //AsyncTask对象的当前状态为Running/Finished,调用execute()会抛出异常
           //不能对正在执行任务或已经执行完任务的AsyncTask对象调用execute方法
            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;
       //调用execute()方法会自动调用onPreExecute()方法,无需手动调用
        onPreExecute();

        mWorker.mParams = params;
        //mFuture ————封装后台任务的FutureTask对象(该对象实现FutureRunnable接口,便于取消后台任务及获取后台任务的执行结果)
        exec.execute(mFuture);

        return this;
    }

基于以上分析后,任务被提交到线程池执行,接下来回头看一下AsyncTask类的构造器

 public AsyncTask() {
        //包含AsyncTask最终要执行的任务(mWorker的call方法)
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
               //表示当前任务已经被调用过
                mTaskInvoked.set(true);
                //设置线程的优先级
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //调用AsyncTask对象的doInBackground()方法开始执行后台任务,并将返回结果传递给postResult()方法
                return postResult(doInBackground(mParams));
            }
        };
        //传入mWorker作为参数
        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);
                }
            }
        };
    }

mFuture 使用的是FutureTask()下面的构造方法

public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

接下来分析postResult()方法

private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        //getHandler()方法获取AsyncTask对象内部包含的sHandler,然后通过它发送MESSAGE_POST_RESULT消息
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

 private static Handler getHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler();
            }
            return sHandler;
        }
    }

private static class InternalHandler extends Handler {
        public InternalHandler() {
            super(Looper.getMainLooper());
        }

        @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;
            }
        }
    }

sHandler 是一个静态的Handler对象,创建Handler对象需要当前线程的Looper,为了以后能够通过sHandler将执行环境从后台线程切换到主线程(在主线程中执行handleMessage方法),所以必须使用主线程的Looper,因此必须在主线程中创建sHandler,这就解释了之前提到的必须在主线程中加载AsyncTask类。

以上为AsyncTask大概的内部运行逻辑,本文是在学习深入理解Android之AsyncTask后进行总结,便于日后复习巩固~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值