AsycnTask

一、异步任务加载网络数据:

在Android中提供了一个异步任务的类AsyncTask,简单来说,这个类中的任务是运行在后台线程中的,并可以将结果放到UI线程中进行处理,它定义了三种泛型,分别是Params、Progress和Result,分别表示请求的参数、任务的进度和获得的结果数据。

1、使用原因:

1)是其中使用了线程池技术,而且其中的方法很容易实现调用

2)可以调用相关的方法,在开启子线程前和后,进行界面的更新

3)一旦任务多了,不用每次都new新的线程,可以直接使用

2、执行的顺序:

onPreExecute()【执行前开启】--- > doInBackground() --- > onProgressUpdate() --- > onPostExecute()

3、执行过程:

当一个异步任务开启后,执行过程如下:

1)、onPreExecute():

这个方法是执行在主线程中的。这步操作是用于准备好任务的,作为任务加载的准备工作。建议在这个方法中弹出一个提示框。

2)、doInBackground():

这个方法是执行在子线程中的。在onPreExecute()执行完后,会立即开启这个方法,在方法中可以执行耗时的操作。需要将请求的参数传递进来,发送给服务器,并将获取到的数据返回,数据会传给最后一步中;这些值都将被放到主线程中,也可以不断的传递给下一步的onProgressUpdate()中进行更新。可以通过不断调用publishProgress(),将数据(或进度)不断传递给onProgressUpdate()方法,进行不断更新界面。

3)、onProgressUpdate():

这个方法是执行在主线程中的。publishProgress()在doInBackground()中被调用后,才开启的这个方法,它在何时被开启是不确定的,执行这个方法的过程中,doInBackground()是仍在执行的,即子线程还在运行着。

4)、onPostExecute():

这个方法是执行在主线程中的。当后台的子线程执行完毕后才调用此方法。doInBackground()返回的结果会作为参数被传递过来。可以在这个方法中进行更新界面的操作。

5)、execute():

       最后创建AsyncTask自定义的类,开启异步任务。

3、实现原理:

1)、线程池的创建:

在创建了AsyncTask的时候,会默认创建一个线程池ThreadPoolExecutor,并默认创建出5个线程放入到线程池中,最多可防128个线程;且这个线程池是公共的唯一一份。

2)、任务的执行:

在execute中,会执行run方法,当执行完run方法后,会调用scheduleNext()不断的从双端队列中轮询,获取下一个任务并继续放到一个子线程中执行,直到异步任务执行完毕。

3)、消息的处理:

在执行完onPreExecute()方法之后,执行了doInBackground()方法,然后就不断的发送请求获取数据;在这个AsyncTask中维护了一个InternalHandler的类,这个类是继承Handler的,获取的数据是通过handler进行处理和发送的。在其handleMessage方法中,将消息传递给onProgressUpdate()进行进度的更新,也就可以将结果发送到主线程中,进行界面的更新了。

4、需要注意的是:

①、这个AsyncTask类必须由子类调用

②、虽然是放在子线程中执行的操作,但是不建议做特别耗时的操作,如果操作过于耗时,建议使用线程池ThreadPoolExecutor和FutureTask

示例代码:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

    protected Long doInBackground(URL... urls) {

        int count = urls.length;

        long totalSize = 0;

        for (int i = 0; i < count; i++) {

            totalSize += Downloader.downloadFile(urls[i]);

            publishProgress((int) ((i / (float) count) * 100));

            // Escape early if cancel() is called

            if (isCancelled()) break;

        }

        return totalSize;

    }

    protected void onProgressUpdate(Integer... progress) {

        setProgressPercent(progress[0]);

    }

    protected void onPostExecute(Long result) {

        showDialog("Downloaded " + result + " bytes");

    }

}

new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask机制

  • AsyncTask必需会用到的三个方法

    • onPreExeCute
    • doInBackground
    • onPostExecute
  • AsyncTask的execute方法,开始执行异步任务,在此方法体中

    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        ...
    
        mStatus = Status.RUNNING;
    
        //调用onPreExecute方法
        onPreExecute();
    
        //把参数赋值给mWorker对象
        mWorker.mParams = params;
        //线程池对象执行mFuture
        sExecutor.execute(mFuture);
    
        return this;
    }
    
  • mWorker是什么类型?,在AsyncTask的构造方法中

    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return doInBackground(mParams);
        }
    };
    
  • 然后把mWorker对象封装至FutureTask对象

    mFuture = new FutureTask<Result>(mWorker)
    
  • 在FutureTask的构造中,又把mWorker封装给Sync对象

    public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
        sync = new Sync(callable);
    }
    
  • 在Sync的构造方法中

    Sync(Callable<V> callable) {
        //这里的callable就是mWorker
        this.callable = callable;
    }
    
  • 线程池执行mFuture对象,此对象是FutureTask的对象,而FutureTask实现了Runnable接口

    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    ...
    
    //线程池对象执行mFuture
    sExecutor.execute(mFuture);
    ...
    

    }

  • mFuture的run方法被调用了

    public void run() {
        sync.innerRun();
    }
    
  • 在innerRun方法中,调用了callable的call方法,但是在sync被new出来的时候,在构造方法中就已经把mWorker赋值给了callable,所以实际上是调用mWorker的call方法

    void innerRun() {
        ...
            //调用mWorker的call()
            result = callable.call();
    
            set(result);
        ...
    }
    
  • mWorker的call在mWorker被new出来时就已经重写了

    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
           ...
            //在子线程中调用了doInBackground方法
            return doInBackground(mParams);
        }
    };
    
  • call方法调用完毕后,得到doInBackground所返回的result

    void innerRun() {
        ...
            result = callable.call();
            //返回的result传入了set方法
            set(result);
        ...
    }
    
  • set方法体

    protected void set(V v) {
         sync.innerSet(v);
    }
    
  • innerSet方法体

     if (compareAndSetState(s, RAN)) {
                result = v;
                releaseShared(0);
                //关键的done方法
                done();
                return;
      }
    
  • innerSet方法是属于FutureTask类的,那么done方法也是调用FutureTask类的,这个done方法定义的地方,在AsyncTask.java的构造方法里

    mFuture = new FutureTask<Result>(mWorker) {
        //此处重写done方法
        @Override
        protected void done() {
    
    
           //获取doInbackground方法返回的结果
            result = get();
    
            //创建一个消息
            message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskResult<Result>(AsyncTask.this, result));
            //把这条消息发送给创建这个消息的Handler:target.sendMessage(this)
            message.sendToTarget();
        }
    };
    
  • 然后sHandler的handlerMessage被触发

    public void handleMessage(Message msg) {
        AsyncTaskResult result = (AsyncTaskResult) msg.obj;
        switch (msg.what) {
            case MESSAGE_POST_RESULT:
                //调用finish方法
                result.mTask.finish(result.mData[0]);
                break;
    
        }
    }
    
  • finish的方法体

    private void finish(Result result) {
     if (isCancelled()) result = null;
        //调用onPostExecute方法,并传入结果
        onPostExecute(result);
        mStatus = Status.FINISHED;
    }
原文地址:https://www.cnblogs.com/dubo-/p/6676091.html