Android中AsyncTask的工作原理 浅谈Android中AsyncTask的工作原理

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android中AsyncTask的工作原理 浅谈Android中AsyncTask的工作原理

handsome黄   2021-06-08 我要评论
想了解浅谈Android中AsyncTask的工作原理的相关内容吗,handsome黄在本文为您仔细讲解Android中AsyncTask的工作原理的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,AsyncTask,下面大家一起来学习吧。

概述

实际上,AsyncTask内部是封装了Thread和Handler。虽然AsyncTask很方便的执行后台任务,以及在主线程上更新UI,但是,AsyncTask并不合适进行特别耗时的后台操作,对于特别耗时的任务,个人还是建议使用线程池。好了,话不多说了,我们先看看AsyncTask的简单用法吧。

AsyncTask使用方法

AsyncTask是一个抽象的泛型类。简单的介绍一下它的使用方式代码如下:

package com.example.huangjialin.myapplication;


import android.os.AsyncTask;

import android.util.Log;


public class AsyncTaskTest extends AsyncTask<String, Object, Long>{


    @Override

    protected void onPreExecute() {

        super.onPreExecute();

        Log.i("AsyncTaskTest","---准备下载---");

    }



    @Override

    protected Long doInBackground(String... params) {



        Log.i("AsyncTaskTest","---在后台正在下载---");

        return null;

    }


    @Override

    protected void onProgressUpdate(Object... values) {

        super.onProgressUpdate(values);

        Log.i("AsyncTaskTest","---在更新---");

    }



    @Override

    protected void onPostExecute(Long aLong) {

        super.onPostExecute(aLong);

        Log.i("AsyncTaskTest","---下载完成,将结果返回到主线程--");

    }

}

然后在activity中调用 new AsyncTaskTest().execute();就可以了...使用起来比较简单,这里就不在讲述怎么使用了。

AsyncTask的4个核心方法

1、onPreExecute():该方法在主线程中执行,在执行异步任务之前会被调用,一般用于一些准备工作。

2、doInBackground(String... params):这个方法是在线程池中执行,此方法用于执行异步任务。在这个方法中可以通过publishProgress方法来更新任务的进度,publishProgress方法会调用onProgressUpdate方法,另外,任务的结果返回给onPostExecute方法。

3、onProgressUpdate(Object... values):该方法在主线程中执行,主要用于任务进度更新的时候,该方法会被调用。

4、onPostExecute(Long aLong):在主线程中执行,在异步任务执行完毕之后,该方法会被调用,该方法的参数及为后台的返回结果。

除了这几个方法之外还有一些不太常用的方法,如onCancelled(),在异步任务取消的情况下,该方法会被调用。

好了,AsyncTask基本的使用就介绍到这里,下面我们进入主题,我们一起看看AsyncTask的工作原理。

AsyncTask的工作原理

先从execute走起,源码来了

@MainThread

    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;

        exec.execute(mFuture);



        return this;

    }

为了方面分析,我就把英文注释干掉了…源码可以知道从上面的execute方法内部调用的是executeOnExecutor()方法。而sDefaultExecutor实际上是一个串行的线程池。而onPreExecute()方法在这里就会被调用了。接着看这个线程池。

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

            }

        }

    }



public AsyncTask() {

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

                }

            }

        };

    }

从上面的代码可以知道,AsyncTask的执行是排队执行的,因为有关键字synchronized,而AsyncTask的Params参数就封装成为FutureTask类,FutureTask这个类是一个并发类,在这里它充当了Runnable的作用。接着FutureTask会交给SerialExecutor的execute方法去处理,而SerialExecutor的executor方法首先就会将FutureTask添加到mTasks队列中,如果这个时候没有任务,就会调用scheduleNext()方法,执行下一个任务。如果有任务的话,则执行完毕后最后在调用 scheduleNext();执行下一个任务。直到所有任务被执行完毕。而AsyncTask的构造方法中有一个call()方法,而这个方法由于会被FutureTask的run方法执行。所以最终这个call方法会在线程池中执行。而doInBackground这个方法就是在这里被调用的。我们好好研究一下这个call()方法。

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;

            }

        };


private Result postResult(Result result) {

        @SuppressWarnings("unchecked")

        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,

                new AsyncTaskResult<Result>(this, result));

        message.sendToTarget();

        return result;

    }

mTaskInvoked.set(true);表示当前任务已经执行过了。接着执行doInBackground方法,最后将结果通过postResult(result);方法进行传递。postResult()方法中通过sHandler来发送消息,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;

            }

        }

    }


private void finish(Result result) {

        if (isCancelled()) {

            onCancelled(result);

        } else {

            onPostExecute(result);

        }

        mStatus = Status.FINISHED;

    }

注意:AsyncTask中有两个线程池,一个是SerialExecutor,另一个是THREAD_POOL_EXECUTOR,其中前者主要是任务进行排队的,后者才是真正的执行任务。

而AsyncTask中还有一个方法InternalHandler,这个方法的主要作用是将执行环境从线程池切换到主线程的。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们