AsyncTask

1. 容易處理 ui 線程

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

2. helper

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.

  1. AsyncTasks should ideally be used for short operations (a few seconds at the most.)
  2. If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
3
An asynchronous task is defined by 3 generic types, called Params, Progress and Result,
4
and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Developer Guides

For more information about using tasks and threads, read the Processes and Threads developer guide.

使用

繼承
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground), and most often will override a second one (onPostExecute.)

** sample**
Here is an example of subclassing:

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

** exe **
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);

AsyncTask's generic types

The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground, invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate step.
  3. onProgressUpdate, invoked on the UI thread after a call to publishProgress. The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task

**A task can be cancelled at any time by invoking cancel(boolean). **
Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Threading rules

There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of android.os.Build.VERSION_CODES.JELLY_BEAN.
The task instance must be created on the UI thread.
execute must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute, doInBackground, onProgressUpdate manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Memory observability
AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.
Set member fields in the constructor or onPreExecute, and refer to them in doInBackground.
Set member fields in doInBackground, and refer to them in onProgressUpdate and onPostExecute.

執(zhí)行順序

  1. When first introduced, AsyncTasks were executed serially on a single background thread.

  2. Starting with android.os.Build.VERSION_CODES.DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel.

  3. Starting with android.os.Build.VERSION_CODES.HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

  4. If you truly want parallel execution, you can invoke executeOnExecutor(Executor, Object[]) with THREAD_POOL_EXECUTOR.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市详幽,隨后出現(xiàn)的幾起案子沛鸵,更是在濱河造成了極大的恐慌蒙挑,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件融求,死亡現(xiàn)場離奇詭異哼转,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)钧唐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蕉斜,“玉大人逾柿,你說我怎么就攤上這事≌耍” “怎么了机错?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長父腕。 經(jīng)常有香客問我弱匪,道長,這世上最難降的妖魔是什么璧亮? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任萧诫,我火速辦了婚禮,結(jié)果婚禮上枝嘶,老公的妹妹穿的比我還像新娘帘饶。我一直安慰自己,他們只是感情好群扶,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布及刻。 她就那樣靜靜地躺著,像睡著了一般竞阐。 火紅的嫁衣襯著肌膚如雪缴饭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天骆莹,我揣著相機(jī)與錄音颗搂,去河邊找鬼。 笑死幕垦,一個胖子當(dāng)著我的面吹牛丢氢,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播先改,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼卖丸,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了盏道?” 一聲冷哼從身側(cè)響起稍浆,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎猜嘱,沒想到半個月后衅枫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡朗伶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年弦撩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片论皆。...
    茶點(diǎn)故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡益楼,死狀恐怖猾漫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情感凤,我是刑警寧澤悯周,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站陪竿,受9級特大地震影響禽翼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜族跛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一闰挡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧礁哄,春花似錦长酗、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至掏膏,卻和暖如春劳翰,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背馒疹。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工佳簸, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人颖变。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓生均,卻偏偏與公主長得像,于是被迫代替她去往敵國和親腥刹。 傳聞我的和親對象是個殘疾皇子马胧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容

  • M給我發(fā)來一條很長的消息佩脊,吐槽剛結(jié)婚的小七男...
    小野姑娘閱讀 324評論 0 0
  • 我活在痛苦和失落中很久很久穴肘,因?yàn)閷ψ约荷钌畹氖?我一直覺得自己身上有無數(shù)的毛病歇盼,個子不夠高、身材不夠瘦评抚、化妝技...
    繁花滿枝閱讀 307評論 2 1
  • 無限的神秘豹缀。 何處尋他伯复? 微笑之后, 言語之前邢笙, 便是無限的神秘了啸如。 人類呵! 相愛罷鸣剪, 我們都是長行...
    六年級房廉碧閱讀 200評論 0 0