关闭 x
IT技术网
    技 采 号
    ITJS.cn - 技术改变世界
    • 实用工具
    • 菜鸟教程
    IT采购网 中国存储网 科技号 CIO智库

    IT技术网

    IT采购网
    • 首页
    • 行业资讯
    • 系统运维
      • 操作系统
        • Windows
        • Linux
        • Mac OS
      • 数据库
        • MySQL
        • Oracle
        • SQL Server
      • 网站建设
    • 人工智能
    • 半导体芯片
    • 笔记本电脑
    • 智能手机
    • 智能汽车
    • 编程语言
    IT技术网 - ITJS.CN
    首页 » 安卓开发 »Android应用AsyncTask处理机制详解及源码分析

    Android应用AsyncTask处理机制详解及源码分析

    2015-07-11 00:00:00 出处:oschina
    分享

    1 背景

    Android异步处理机制一直都是Android的一个核心,也是应用工程师面试的一个知识点。前面我们分析了Handler异步机制原理(不了解的可以阅读我的《Android异步消息处理机制详解及源码分析》文章),这里继续分析Android的另一个异步机制AsyncTask的原理。

    当使用线程和Handler组合实现异步处理时,当每次执行耗时操作都创建一条新线程进行处理,性能开销会比较大。为了提高性能我们使用AsyncTask实现异步处理(其实也是线程和handler组合实现),因为其内部使用了java提供的线程池技术,有效的降低了线程创建数量及限定了同时运行的线程数,还有一些针对性的对池的优化操作。所以说AsyncTask是Android为我们提供的方便编写异步任务的工具类。

    2 实例演示

    先看下使用AsyncTask模拟下载的效果图:

    这里写图片描述

    看下代码,如下:

    public class MainActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main);
    
            new TestAsyncTask(this).execute();
        }
    
        static final class TestAsyncTask extends AsyncTask<Void, Integer, Boolean> {
            //如上三个泛型参数从左到右含义依次为:
            //1. 在执行AsyncTask时需要传入的参数,可用于在后台任务中使用。
            //2. 后台任务执行时,假如需要在界面上显示当前的进度,则使用这个。
            //3. 当任务执行完毕后,假如需要对结果进行返回,则使用这个。
            private Context mContext = null;
            private ProgressDialog mDialog = null;
            private int mCount = 0;
    
            public TestAsyncTask(Context context) {
                mContext = context;
            }
    
            //在后台任务开始执行之间调用,用于进行一些界面上的初始化操作
            protected void onPreExecute() {
                super.onPreExecute();
                mDialog = new ProgressDialog(mContext);
                mDialog.setMax(100);
                mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mDialog.show();
            }
    
            //这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任务
            protected Boolean doInBackground(Void... params) {
                while (mCount < 100) {
                    publishProgress(mCount);
                    mCount += 20;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return true;
            }
    
            //当在后台任务中调用了publishProgress(Progress...)方法后,这个方法就很快会被调用
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                mDialog.setProgress(values[0]);
            }
    
            //当后台任务执行完毕并通过return语句进行返回时,这个方法就很快会被调用
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                if (aBoolean && mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }
        }
    }

    可以看见Android帮我们封装好的AsyncTask还是很方便使用的,咱们不做过多说明。接下来直接分析源码。

    3 Android5.1.1(API 22)AsyncTask源码分析

    通过源码可以发现AsyncTask是一个抽象类,所以我们在在上面使用时需要实现它。

    那怎么下手分析呢?很简单,我们就依据上面示例的流程来分析源码,具体如下。

    3-1 AsyncTask实例化源码分析

        /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
    
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    return postResult(doInBackground(mParams));
                }
            };
    
            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);
                    }
                }
            };
        }

    看见注释没有,AsyncTask的实例化只能在UI线程中。然后整个构造函数就只初始化了两个AsyncTask类的成员变量(mWorker和mFuture)。mWorker为匿名内部类的实例对象WorkerRunnable(实现了Callable接口),mFuture为匿名内部类的实例对象FutureTask,传入了mWorker作为形参(重写了FutureTask类的done方法)。

    3-2 AsyncTask的execute方法源码分析

    正如上面实例一样,得到AsyncTask实例化对象之后就执行了execute方法,所以看下execute方法的源码,如下:

        public final AsyncTask<Params, Progress, Result> execute(Params... params) {
            return executeOnExecutor(sDefaultExecutor, params);
        }

    可以看见,execute调运了executeOnExecutor方法,executeOnExecutor方法除过传入了params形参以外,还传入了一个static的SerialExecutor对象(SerialExecutor实现了Executor接口)。继续看下executeOnExecutor源码,如下:

        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异步任务的状态,当处于RUNNING和FINISHED时就报IllegalStateException非法状态异常。由此可以看见一个AsyncTask的execute方法只能被调运一次。接着看见17行onPreExecute();没有?看下这个方法源码,如下:

        /**
         * Runs on the UI thread before {@link #doInBackground}.
         *
         * @see #onPostExecute
         * @see #doInBackground
         */
        protected void onPreExecute() {
        }

    空方法,而且通过注释也能看见,这不就是我们AsyncTask中第一个执行的方法吗?是的。

    回过头继续往下看,看见20行exec.execute(mFuture);代码没?exec就是形参出入的上面定义的static SerialExecutor对象(SerialExecutor实现了Executor接口),所以execute就是SerialExecutor静态内部类的方法喽,在执行execute方法时还传入了AsyncTask构造函数中实例化的第二个成员变量mFuture。我们来看下SerialExecutor静态内部类的代码,如下:

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

    在源码中可以看见,SerialExecutor在AsyncTask中是以常量的形式被使用的,所以在整个应用程序中的所有AsyncTask实例都会共用同一个SerialExecutor对象。

    接着可以看见,SerialExecutor是使用ArrayDeque这个队列来管理Runnable对象的,假如我们一次性启动了很多个任务,首先在第一次运行execute()方法的时候会调用ArrayDeque的offer()方法将传入的Runnable对象添加到队列的最后,然后判断mActive对象是不是等于null,第一次运行是null,然后调用scheduleNext()方法,在这个方法中会从队列的头部取值,并赋值给mActive对象,然后调用THREAD_POOL_EXECUTOR去执行取出的取出的Runnable对象。之后假如再有新的任务被执行时就等待上一个任务执行完毕后才会得到执行,所以说同一时刻只会有一个线程正在执行,其余的均处于等待状态,这就是SerialExecutor类的核心作用。

    我们再来看看上面用到的THREAD_POOL_EXECUTOR与execute,如下:

    public abstract class AsyncTask<Params, Progress, Result> {
        ......
        private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
        private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
        private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
        private static final int KEEP_ALIVE = 1;
    
        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());
            }
        };
    
        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
                = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                        TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
        ......
    }

    看见没有,实质就是在一个线程池中执行,这个THREAD_POOL_EXECUTOR线程池是一个常量,也就是说整个App中不论有多少AsyncTask都只有这一个线程池。也就是说上面SerialExecutor类中execute()方法的所有逻辑就是在子线程中执行,注意SerialExecutor的execute方法有一个Runnable参数,这个参数就是mFuture对象,所以我们看下FutureTask类的run()方法,如下源码:

        public void run() {
            if (state != NEW ||
                !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                             null, Thread.currentThread()))
                return;
            try {
                Callable<V> c = callable;
                if (c != null && state == NEW) {
                    V result;
                    boolean ran;
                    try {
                        result = c.call();
                        ran = true;
                    } catch (Throwable ex) {
                        result = null;
                        ran = false;
                        setException(ex);
                    }
                    if (ran)
                        set(result);
                }
            } finally {
                // runner must be non-null until state is settled to
                // prevent concurrent calls to run()
                runner = null;
                // state must be re-read after nulling runner to prevent
                // leaked interrupts
                int s = state;
                if (s >= INTERRUPTING)
                    handlePossibleCancellationInterrupt(s);
            }
        }

    看见没有?第7行的c = callable;其实就是AsyncTask构造函数中实例化FutureTask对象时传入的参数mWorker。12行看见result = c.call();没有?其实就是调运WorkerRunnable类的call方法,所以我们回到AsyncTask构造函数的WorkerRunnable匿名内部内中可以看见如下:

    mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
    
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    return postResult(doInBackground(mParams));
                }
            };

    看见没有?在postResult()方法的参数里面,我们可以看见doInBackground()方法。所以这验证了我们上面例子中使用的AsyncTask,首先在主线程执行onPreExecute方法,接着在子线程执行doInBackground方法,所以这也就是为什么我们可以在doInBackground()方法中去处理耗时操作的原因了,接着等待doInBackground方法耗时操作执行完毕以后将返回值传递给了postResult()方法。所以我们来看下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拿到的是哪个Handler吧,如下:

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

    看见没有,拿到的是MainLooper,也就是说在在UI线程中的Handler(不清楚的请阅读《Android异步消息处理机制详解及源码分析》文章)。所以上面的方法其实就是将子线程的数据发送到了UI来处理,也就是通过MESSAGE_POST_RESULT在handleMessage来处理。所以我们继续看handleMessage中的result.mTask.finish(result.mData[0]);就会发现finish的代码如下:

        private void finish(Result result) {
            if (isCancelled()) {
                onCancelled(result);
            } else {
                onPostExecute(result);
            }
            mStatus = Status.FINISHED;
        }

    看见没有?依据返回值true与false回调AsyncTask的onPostExecute或者onCancelled方法。

    到此是不是会好奇onProgressUpdate方法啥时候调运的呢?继续往下看可以发现handleMessage方法中的MESSAGE_POST_PROGRESS不就是回调我们UI Thread中的onProgressUpdate方法吗?那怎么样才能让他回调呢?追踪MESSAGE_POST_PROGRESS消息你会发现如下:

        protected final void publishProgress(Progress... values) {
            if (!isCancelled()) {
                getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                        new AsyncTaskResult<Progress>(this, values)).sendToTarget();
            }
        }

    额,没意思了。这不就是我们上面例子中的在子线程的doInBackground耗时操作中调运通知回调onProgressUpdate的方法么。

    看见没有,AsyncTask的实质就是Handler异步消息处理机制(不清楚的请阅读《Android异步消息处理机制详解及源码分析》文章),只是对线程做了优化处理和封装而已。

    4 为当年低版本AsyncTask的臭名正身

    接触Android比较久的可能都知道,在Android 3.0之前是并没有SerialExecutor这个类的(上面有分析)。那些版本的代码是直接创建了指定大小的线程池常量来执行task的。其中MAXIMUM_POOL_SIZE = 128;,所以那时候假如我们应用中一个界面需要同时创建的AsyncTask线程大于128(批量获取数据,譬如照片浏览瀑布流一次加载)程序直接就挂了。所以当时的AsyncTask因为这个原因臭名昭著。

    回过头来看看现在高版本的AsyncTask,是不是没有这个问题了吧?因为现在是顺序执行的。而且更劲爆的是现在的AsyncTask还直接提供了客户化实现Executor接口功能,使用如下方法执行AsyncTask即可使用自定义Executor,如下:

        public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
                Params... params) {
            ......
            return this;
        }

    可以看出,在3.0以上版中AsyncTask已经不存在那个臭名昭著的Bug了,所以可以放心使用了,妈妈再也不用担心我的AsyncTask出Bug了。

    5 AsyncTask与Handler异步机制对比

    前面文章也分析过Handler了,这里也分析了AsyncTask,现在把他们两拽一起来比较比较。具体如下:

    AsyncTask是对Handler与Thread的封装。 AsyncTask在代码上比Handler要轻量级别,但实际上比Handler更耗资源,因为AsyncTask底层是一个线程池,而Handler仅仅就是发送了一个消息队列。但是,假如异步任务的数据特别庞大,AsyncTask线程池比Handler节省开销,因为Handler需要不停的new Thread执行。 AsyncTask的实例化只能在主线程,Handler可以随意,只和Looper有关系。

    6 AsyncTask总结

    到此整个Android的AsyncTask已经分析完毕,相信你现在对于AsyncTask会有一个很深入的理解与认识了。

    上一篇返回首页 下一篇

    声明: 此文观点不代表本站立场;转载务必保留本文链接;版权疑问请联系我们。

    别人在看

    Linux 退出 mail的命令是什么

    Linux 提醒 No space left on device,但我的空间看起来还有不少空余呢

    hiberfil.sys文件可以删除吗?了解该文件并手把手教你删除C盘的hiberfil.sys文件

    Window 10和 Windows 11哪个好?答案是:看你自己的需求

    盗版软件成公司里的“隐形炸弹”?老板们的“法务噩梦” 有救了!

    帝国CMS7.5编辑器上传图片取消宽高的三种方法

    帝国cms如何自动生成缩略图的实现方法

    Windows 12即将到来,将彻底改变人机交互

    帝国CMS 7.5忘记登陆账号密码怎么办?可以phpmyadmin中重置管理员密码

    帝国CMS 7.5 后台编辑器换行,修改回车键br换行为p标签

    IT头条

    智能手机市场风云:iPhone领跑销量榜,华为缺席引争议

    15:43

    大数据算法和“老师傅”经验叠加 智慧化收储粮食尽显“科技范”

    15:17

    严重缩水!NVIDIA将推中国特供RTX 5090 DD:只剩24GB显存

    00:17

    无线路由大厂 TP-Link突然大裁员:补偿N+3

    02:39

    Meta 千万美金招募AI高级人才

    00:22

    技术热点

    Spring基础知识汇总 Java开发必看

    SQL Server索引与其性能的描述

    SQL Server 2008数据格式修改时应注意什么?

    如何禁止windows 7网络搜索驱动?windows 7禁止网络搜索驱动的方

    SQL Server系统表中的sysconfigures表

    如何恢复windows 7、windows 8图片预览功能详细图解

      友情链接:
    • IT采购网
    • 科技号
    • 中国存储网
    • 存储网
    • 半导体联盟
    • 医疗软件网
    • 软件中国
    • ITbrand
    • 采购中国
    • CIO智库
    • 考研题库
    • 法务网
    • AI工具网
    • 电子芯片网
    • 安全库
    • 隐私保护
    • 版权申明
    • 联系我们
    IT技术网 版权所有 © 2020-2025,京ICP备14047533号-20,Power by OK设计网

    在上方输入关键词后,回车键 开始搜索。Esc键 取消该搜索窗口。