Android AsyncTask實(shí)現(xiàn)機(jī)制詳細(xì)介紹及實(shí)例代碼
Android AsyncTask實(shí)現(xiàn)機(jī)制
示例代碼:
public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } 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先調(diào)用onPreExecute()(可見,onPreExecute是自動(dòng)調(diào)用的)然后調(diào)用exec.execute(mFuture)
public interface Executor { void execute(Runnable command); }
這是一個(gè)接口,具體實(shí)現(xiàn)在
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); } } }
從上面可知,AsyncTask執(zhí)行過程如下:先執(zhí)行onPreExecute,然后交給SerialExecutor執(zhí)行。在SerialExecutor中,先把Runnable添加到mTasks中。
如果沒有Runnable正在執(zhí)行,那么就調(diào)用SerialExecutor的scheduleNext。同時(shí)當(dāng)一個(gè)Runnable執(zhí)行完以后,繼續(xù)執(zhí)行下一個(gè)任務(wù)
AsyncTask中有兩個(gè)線程池,THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR,以及一個(gè)Handler–InternalHandler
/** * 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); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static InternalHandler sHandler;
SERIAL_EXECUTOR用于任務(wù)的排列,THREAD_POOL_EXECUTOR真正執(zhí)行線程,InternalHandler用于線程切換
先看構(gòu)造函數(shù)
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); } } }; }
看到了熟悉的doInBackground了吧,然后調(diào)用postResult
private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; }
主線程中創(chuàng)建InternalHandler并發(fā)送MESSAGE_POST_RESULT消息,然后調(diào)用finish函數(shù)
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; }
finish中調(diào)用onPostExecute。
AsyncTask工作流程:new MyThread().execute(1);
先構(gòu)造函數(shù),然后execute
構(gòu)造函數(shù)只是準(zhǔn)備了mWorker和mFuture這兩個(gè)變量
execute中調(diào)用onPreExecute,然后exec.execute(mFuture),其中響應(yīng)了call函數(shù),call中調(diào)用doInBackground,然后將結(jié)果傳給Handler然后finish掉,finish函數(shù)調(diào)用onPostExecute
你可能會(huì)奇怪,為什么沒有onProgressUpdate,有注解可以解釋
/** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { }
也就是說(shuō)必須調(diào)用publishProgress才會(huì)自動(dòng)調(diào)用onProgressUpdate。
那如何調(diào)用publishProgress呢?
/** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params);
doInBackground說(shuō)的很明確,在doInBackground函數(shù)里面顯示調(diào)用publishProgress即可。
publishProgress源碼:
protected final void publishProgress(Progress... values) { if (!isCancelled()) { getHandler().obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } 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: //****************************************在這里調(diào)用 result.mTask.onProgressUpdate(result.mData); break; } } }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
- Android帶進(jìn)度條的文件上傳示例(使用AsyncTask異步任務(wù))
- Android中通過AsyncTask類來(lái)制作炫酷進(jìn)度條的實(shí)例教程
- Android AsyncTask用法巧用實(shí)例代碼
- Android屏幕旋轉(zhuǎn) 處理Activity與AsyncTask的最佳解決方案
- Android中使用AsyncTask實(shí)現(xiàn)文件下載以及進(jìn)度更新提示
- 詳解Android App中的AsyncTask異步任務(wù)執(zhí)行方式
- Android AsyncTask完全解析 帶你從源碼的角度徹底理解
- Android AsyncTask源碼分析
- Android中使用AsyncTask做下載進(jìn)度條實(shí)例代碼
相關(guān)文章
Android實(shí)現(xiàn)拍照、選擇相冊(cè)圖片并裁剪功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)拍照、選擇相冊(cè)圖片并裁剪功能的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12非常實(shí)用的側(cè)滑刪除控件SwipeLayout
這篇文章主要為大家詳細(xì)介紹了非常實(shí)用的側(cè)滑刪除控件SwipeLayout,類似于QQ側(cè)滑點(diǎn)擊刪除效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08Android開發(fā)實(shí)現(xiàn)ListView點(diǎn)擊item改變顏色功能示例
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)ListView點(diǎn)擊item改變顏色功能,涉及Android布局及響應(yīng)事件動(dòng)態(tài)變換元素屬性相關(guān)操作技巧,需要的朋友可以參考下2017-11-11Android 多線程實(shí)現(xiàn)重復(fù)啟動(dòng)與停止的服務(wù)
這篇文章主要介紹了Android 多線程實(shí)現(xiàn)重復(fù)啟動(dòng)與停止的服務(wù)的相關(guān)資料,多線程環(huán)境下為了避免死鎖,一般提倡開放調(diào)用,開放調(diào)用可以避免死鎖,它的代價(jià)是失去原子性,這里說(shuō)明重復(fù)啟動(dòng)與停止的服務(wù),需要的朋友可以參考下2017-08-08Android ListView與getView調(diào)用卡頓問題解決辦法
這篇文章主要介紹了Android ListView與getView調(diào)用卡頓問題解決辦法的相關(guān)資料,這里提供實(shí)例及解決辦法幫助大家解決這種問題,需要的朋友可以參考下2017-08-08Android實(shí)現(xiàn)測(cè)試環(huán)境噪音分貝
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)測(cè)試環(huán)境噪音分貝,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Android實(shí)現(xiàn)錄音方法(仿微信語(yǔ)音、麥克風(fēng)錄音、發(fā)送語(yǔ)音、解決5.0以上BUG)
大家平時(shí)在使用微信qq聊天時(shí)經(jīng)常會(huì)發(fā)送語(yǔ)音功能,今天小編給大家?guī)?lái)了基于android實(shí)現(xiàn)錄音的方法仿微信語(yǔ)音、麥克風(fēng)錄音、發(fā)送語(yǔ)音、解決5.0以上BUG,需要的朋友參考下吧2018-04-04android使用SharedPreferences進(jìn)行數(shù)據(jù)存儲(chǔ)
Android平臺(tái)給我們提供了一個(gè)SharedPreferences類,它是一個(gè)輕量級(jí)的存儲(chǔ)類,特別適合用于保存軟件配置參數(shù)。有興趣的可以了解一下。2017-02-02