前言
之前執(zhí)行異步任務(wù),都是采用Thread+Handler模式,為每個(gè)任務(wù)創(chuàng)建一個(gè)線程惜辑,需要更新UI時(shí)鳞绕,通過(guò)Handler發(fā)送消息通知主線程執(zhí)行相應(yīng)操作。一直用開(kāi),雖然代碼臃腫點(diǎn),但功能上還是能實(shí)現(xiàn)。最近這個(gè)項(xiàng)目就出現(xiàn)了問(wèn)題打毛,需要頻繁地在幾個(gè)操作中循環(huán)執(zhí)行,就需要不斷地new Thread俩功,數(shù)量一多起來(lái)幻枉,就無(wú)法實(shí)現(xiàn)對(duì)線程的精確控制了。
源碼分析
async task 源碼很短诡蜓,總共都不到700行展辞,我們直接從源碼入手,看一下它的實(shí)現(xiàn)套路万牺。
AsyncTask enables proper and easy use of the UI thread. This class allows to?perform background operations and publish results on the UI thread withouthaving to manipulate threads and/or handlers.
注釋的第一部分就道出了 async task的主要作用:提供了一種更合理罗珍、更便利的方式用于更新ui.
構(gòu)造函數(shù)
public abstract classAsyncTask<Params,Progress,Result>??{...}
publicAsyncTask() {...}
系統(tǒng)提供了兩個(gè)構(gòu)造函數(shù),一個(gè)是帶參的脚粟,一個(gè)是無(wú)參的覆旱,用戶可根據(jù)自己業(yè)務(wù)需要來(lái)構(gòu)建。帶參方法的三個(gè)參數(shù)含義如下:
Params, the type of the parameters sent to the task upon *? ? execution.(啟動(dòng)任務(wù)時(shí)的輸入?yún)?shù))
Progress, the type of the progress units published during *? ? the background computation.(執(zhí)行任務(wù)的進(jìn)度)
Result, the type of the result of the background *? ? computation.(返回結(jié)果的類型)
核心方法
1.execute:
源碼:
@MainThread
public finalAsyncTaskexecute(Params... params){
return executeOnExecutor(sDefaultExecutor,params);
}
主線程調(diào)用此方法核无,觸發(fā)異步線程的執(zhí)行扣唱。
2.onPreExecute:
源碼:
/**?Runs on the UI thread before {@link#doInBackground}
@see#onPostExecute
@see#doInBackground*/
@MainThread
protected void onPreExecute() {}
異步線程被觸發(fā)后,立即被執(zhí)行团南,主要用于初始化UI噪沙,如將進(jìn)度條的值設(shè)為0。
3.doInBackground:
源碼:
/*Override this method to perform a computation on a background thread*/
@WorkerThread
protected abstract Result doInBackground(Params... params);
執(zhí)行耗時(shí)操作吐根,并返回執(zhí)行類型的結(jié)果正歼。可通過(guò)調(diào)用publishProgress(Progress... values)更新任務(wù)進(jìn)度消息拷橘。
4.onProgressUpdate:
源碼:
/**?Runs on the UI thread after {@link#publishProgress} is invoked.*/
@MainThread
protected void onProgressUpdate(Progress... values) {}
用于更新UI局义,如更新進(jìn)度條當(dāng)前值:progressBar.setProgress(values[0]);
5.onPostExecute:
源碼:
/*Runs on the UI thread after {@link#doInBackground}*/
@MainThread
protected voidonPostExecute(Resultresult) {}
后臺(tái)耗時(shí)操作完成后喜爷,該方法被調(diào)用,主要執(zhí)行更新UI操作萄唇,如:imageView.setImageBitmap(bitmap);
執(zhí)行流程
使用示例
效果圖:
待研究:
1.async task 局限性檩帐。
2.不同版本的兼容性。
3.進(jìn)一步分析源碼另萤。