Android AsyncTask內(nèi)部原理

Android AsyncTask內(nèi)部原理

@(Android)

[toc]

小筆記

基本使用

/**
 * 在主線程中調(diào)用,可以做一些初始化的操作,但是不要在這里做耗時(shí)操作
 */
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

/**
 * 在子線程中調(diào)用,耗時(shí)操作全部在這里完成。
 * 如果需要更新進(jìn)度可以調(diào)用 publishProgress(Progress... values)
 */
@Override
protected Object doInBackground(Object[] params) {
    return null;
}

/**
  * 在主線程中調(diào)用,顯示子線程進(jìn)度的回調(diào)函數(shù)
  * @param values
  */
 @Override
 protected void onProgressUpdate(Object[] values) {
     super.onProgressUpdate(values);
 }

/**
  * 在主線程中調(diào)用,傳入的傳輸是在doInBackground中返回的值
  * @param o
  */
 @Override
 protected void onPostExecute(Object o) {
     super.onPostExecute(o);
}

/**
 * AsyncTask被取消的時(shí)候會(huì)回調(diào)
 * 參數(shù)是從哪里傳過來的呢。后面有解釋
 */
@Override
protected void onCancelled(Object o) {
    super.onCancelled(o);
    System.out.println(o instanceof Bitmap);
    if (o instanceof Bitmap) {
        image_view.setImageBitmap((Bitmap) o);
    }
}
/**
 * AsyncTask被取消的時(shí)候會(huì)回調(diào)
 */
@Override
protected void onCancelled() {
    super.onCancelled();
    System.out.println("MyAsyncTask ========== onCancelled");
}

了解了基本的使用方法之后,簡單的實(shí)現(xiàn)一個(gè)加載圖片的方法吧

package com.example.wen.asynctask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ImageView image_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image_view = (ImageView) findViewById(R.id.image_view);
        new MyAsyncTask().execute();
    }

    class MyAsyncTask extends AsyncTask {

        /**
         * 在主線程中調(diào)用,可以做一些初始化的操作,但是不要在這里做耗時(shí)操作
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * 在子線程中調(diào)用,耗時(shí)操作全部在這里完成。
         * 如果需要更新進(jìn)度可以調(diào)用 publishProgress(Progress... values)
         */
        @Override
        protected Object doInBackground(Object[] params) {

            Bitmap bitmap = null;

            try {
                URL url = new URL("https://www.baidu.com/img/bd_logo1.png");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                bitmap = BitmapFactory.decodeStream(connection.getInputStream());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        }

        /**
         * 在主線程中調(diào)用,傳入的傳輸是在doInBackground中返回的值
         * @param o
         */
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if (o instanceof Bitmap) {
                image_view.setImageBitmap((Bitmap) o);
            }
        }

        /**
         * 在主線程中調(diào)用,顯示子線程進(jìn)度的回調(diào)函數(shù)
         * @param values
         */
        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
        }

        /**
         * AsyncTask被取消的時(shí)候會(huì)回調(diào)
         */
        @Override
        protected void onCancelled(Object o) {
            super.onCancelled(o);
            System.out.println(o instanceof Bitmap);
            if (o instanceof Bitmap) {
                image_view.setImageBitmap((Bitmap) o);
            }
        }
        /**
         * AsyncTask被取消的時(shí)候會(huì)回調(diào)
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
            System.out.println("MyAsyncTask ========== onCancelled");
        }
    }
}

內(nèi)部實(shí)現(xiàn)原理

  1. 在主線程中調(diào)用execute(Params... params)方法或者是指定的線程池的executeOnExecutor(Executor exec,Params... params)
 @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;
}

從上面的代碼中看到兩點(diǎn):

  1. onPreExecute()方法在主線程中調(diào)用的
  2. 另外,在執(zhí)行exec.execute(mFuture);的時(shí)候,會(huì)先判斷mStatus的狀態(tài)。所以每一個(gè)AsyncTask對象都只能調(diào)用execute()方法一次??匆幌耺Statues的定義:
private volatile Status mStatus = Status.PENDING;

public enum Status {
    /**
     * Indicates that the task has not been executed yet.
     */
    PENDING,
    /**
     * Indicates that the task is running.
     */
    RUNNING,
    /**
     * Indicates that {@link AsyncTask#onPostExecute} has finished.
     */
    FINISHED,【
}

從定義中看到mStatus是用volatile關(guān)鍵字修飾的。volatile的作用是保證操作的可見性,即修改之后其他能馬上讀取修改后的值。詳情看Java 并發(fā)編程。
  那為什么需要用一個(gè)volatile關(guān)鍵字修飾呢?,F(xiàn)在有這么一個(gè)場景,一個(gè)AsyncTask對象已經(jīng)快執(zhí)行完后臺(tái)任務(wù)了,準(zhǔn)備修改狀態(tài)Statue.FINISH,但是這個(gè)時(shí)候,主線程保留了這個(gè)AsyncTask對象,并且調(diào)用了execute()方法,這個(gè)時(shí)候就會(huì)導(dǎo)致一個(gè)AsyncTask被調(diào)用了兩次。
  而一個(gè)AsyncTask不允許執(zhí)行兩次的原因是考慮到了線程安全的問題,如果一個(gè)對象被執(zhí)行了兩次,那么就需要考慮自己定義的成員變量的線程安全的問題了。所以直接在new一個(gè)出來比執(zhí)行兩次的方式更加方便。

當(dāng)判斷是第一次調(diào)用的時(shí)候,后面就會(huì)調(diào)用到exec.execute(mFuture);方法。線程池中的exec.execute()需要一個(gè)Runnable的對象,所以讓我們看看mFuture的定義吧:

private final FutureTask<Result> mFuture;

我們發(fā)現(xiàn)他是一個(gè)FutureTask對象。FutrueTask對象需要實(shí)現(xiàn)一個(gè)方法:

 /**
  * Protected method invoked when this task transitions to state
  * {@code isDone} (whether normally or via cancellation). The
  * default implementation does nothing.  Subclasses may override
  * this method to invoke completion callbacks or perform
  * bookkeeping. Note that you can query status inside the
  * implementation of this method to determine whether this task
  * has been cancelled.
  */
protected void done() { }

并且在FutureTask的構(gòu)造方法中,需要傳一個(gè)Callable對象,那么Callable又是一個(gè)什么東西呢。簡單來說,Callable是一個(gè)有返回值的Runnable。所以FutureTask在后臺(tái)運(yùn)行的代碼就是Callable中的call()的方法。具體來看看在AsyncTask源碼中是怎么實(shí)現(xiàn)的:

mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        mTaskInvoked.set(true);

        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        //noinspection unchecked
        Result result = doInBackground(mParams);
        Binder.flushPendingCommands();
        return postResult(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);
        }
    }
};

上面看到的mWorker是一個(gè)實(shí)現(xiàn)了Callable的類,并且用一個(gè)變量保存了在執(zhí)行AsyncTask時(shí)傳入的參數(shù)

private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
    Params[] mParams;
}

上面的代碼的大概意思就是在一個(gè)子線程中調(diào)用了我們實(shí)現(xiàn)的doInBackground()方法。在FutureTask中的done()方法中有一個(gè)get()方法,作用就是獲取doInBackground()返回的數(shù)據(jù)。然后將返回的數(shù)據(jù)傳到postResult方法中:

private Result postResult(Result result) {
   Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
           new AsyncTaskResult<Result>(this, result));
   message.sendToTarget();
   return result;
}

在這里可以看到AsyncTask的內(nèi)部是通過Handler來實(shí)現(xiàn)的。這里還有一個(gè)AsyncTaskResult

 private static class AsyncTaskResult<Data> {
    final AsyncTask mTask;
    final Data[] mData;

    AsyncTaskResult(AsyncTask task, Data... data) {
        mTask = task;
        mData = data;
    }
}

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

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

因?yàn)樵?code>finish()方法中需要判斷Task是否被取消,而Status是對象內(nèi)部的成員變量,所以需要保留一個(gè)AsyncTask對象和在子線程中返回的數(shù)據(jù)。

當(dāng)執(zhí)行完finish()方法之后,基本AsyncTask的內(nèi)部原理都講完了。耶??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容