Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android基礎 -- AsyncTask介紹和使用

Android基礎 -- AsyncTask介紹和使用

編輯:關於Android編程

好久好久沒寫博客了,這一個多月的時間,自己的身體和心理狀態對我來說都是差勁的。不是不想寫博客,而是實在寫不出有觀點的新穎的東西,面臨將要工作這一現實,內心還是有一丟丟擔心和憂慮的。

為了保持良好的博客習慣,我還是把這篇筆記貼了出來,雖然他是翻譯的google的api,但是,希望這篇文章可以幫到和我一樣英語不好的人,讓我們一同進步。

AsynTask

Class Overview


 

 

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.

一種異步處理機制,他不需要操作線程或者使用handler就可以控制UI線程

AsyncTask is designed to be a helper class aroundThreadandHandlerand does not constitute(構成) a generic threading framework. AsyncTasks should ideally be used for(可用於) short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by thejava.util.concurrentpackage such asExecutor,ThreadPoolExecutorandFutureTask.

這一段大概說,這個類只是個為了方便使用thread和handler的輔助類,不能構成一個框架,他只能進行斷的線程操作。要想進行長的線程操作,還要去java.util.concurrent中找Executor,ThreadPoolExecutorandFutureTask(話說這三個是什麼鬼)

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types(泛型), calledParams,ProgressandResult, and 4 steps, calledonPreExecute,doInBackground,onProgressUpdateandonPostExecute.

講了什麼是異步任務,好吧是在翻譯不通順,只能自己寫一下了:就是在非UI線程上進行運算,在然後將結果更新在UI線程上

一個AsynTask的定義通過三種泛型calledParams,ProgressandResultonPreExecute,doInBackground,onProgressUpdateandonPostExecute四個步驟

 

Developer Guides

For more information about using tasks and threads, read theProcesses and Threadsdeveloper guide.

有關更多的使用線程的信息,請讀。。。開發者指南

 

Usage(使用)

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

該類是抽象類,使用必須子類繼承,並至少覆蓋一個方法doInBackground(Params...)而且通常重寫onPostExecute(Result)方法

 

栗子:


  1. private class DownloadFilesTask extends AsyncTask { //注意繼承asynctask要寫泛型
  2. protected Long doInBackground(URL... urls) {
  3. int count = urls.length;
  4. long totalSize = 0;
  5. for (int i = 0; i < count; i++) {
  6. totalSize += Downloader.downloadFile(urls[i]);
  7. publishProgress((int) ((i / (float) count) * 100));
  8. // Escape early if cancel() is called 如果cancel被調用 異步任務將會提早退出
  9. if (isCancelled()) break;
  10. }
  11. return totalSize;
  12. }
  13.  
  14. protected void onProgressUpdate(Integer... progress) {
  15. setProgressPercent(progress[0]);
  16. }
  17.  
  18. protected void onPostExecute(Long result) {
  19. showDialog("Downloaded " + result + " bytes");
  20. }
  21. }

Once created, a task is executed very simply:

這裡是啟動任務的方法:


  1. 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 typeVoid:

這三個泛型不一定都用的上,不用的用void就可以了



 

The 4 steps(三個泛型睾丸,就是四個步驟)


When an asynchronous task is executed, the task goes through 4 steps: 執行一個異步任務 要四部

onPreExecute(), invoked(參與,引用) on the UI thread before the task is executed. This step is normally used to setup the task, for instance(例如) by showing a progress bar in the user interface.

在執行異步任務前,調用該方法,注意:該方法運行在UI線程上。這一步通常用於設置任務,比如通過用戶界面顯示一個進度條

doInBackground(Params...), invoked on the background thread immediately afteronPreExecute()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 usepublishProgress(Progress...)to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)step.

在執行完onPreExecute方法後,立即調用此方法(在非UI線程中),此步驟可以用來進行後台運算,可能會需要較長的時間。前面的參數就是要傳給他的,他接受參數進行處理後,返回的就是Result,不信你看他的返回值。而且他必須返回,然後再把這個返回值傳給最後一步onPostExecute(Result)。

也可以在這個方法中調用publishProgress(Progress...)方法來改變進度。然後用第三步可以更新這些值到UI線程。

onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(Progress...). 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.

在調用publishProgress(Progress...)之後在主線程中調用該方法。他的執行時間沒有定義,該方法用於向用戶顯示progress,同時後台線程仍在運行。

例如,他可以用來動態的更新進度條或日志

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

執行請求。在後台運算完成後調用了用戶UI線程。後台運行的結果以一個參數的形式被傳遞到了這一步。

 

Cancelling a task(取消一個任務)


A task can be cancelled at any time by invokingcancel(boolean).可以在任何時間內隨時取消該任務 Invoking this method will cause subsequent(隨後) calls toisCancelled()to return true. 調用這個方法後,isCancelled()方法將會返回true(這不是廢話嗎)。

After invoking this method,onCancelled(Object), instead ofonPostExecute(Object)will be invoked afterdoInBackground(Object[])returns.

調用該方法後,在doInBackground(Object[])方法返回結果後,將不會調用onPostExecute(Object)方法接受Result,而是調用onCancelled(Object)方法接受Result。(這裡要等到doInBackground(Object[])方法結束後才能正是取消任務,所以需要使用isCancelled()在doInBackGround中判斷)

To ensure that a task is cancelled as quickly as possible, you should always check the return value ofisCancelled()periodically fromdoInBackground(Object[]), if possible (inside a loop for instance.)

為了確保任務可以盡快的取消,如果可以的話,你應該在doInBackground(Object[]中使用isCancelled()檢查一下任務是否被取消了

 

 

 

Threading rules(線程規則)


There are a few threading rules that must be followed for this class to work properly(正常工作):

private class MyTask extends AsyncTask { ... } The AsyncTask class must be loaded on the UI thread. This is done automatically as ofJELLY_BEAN. 這個類必須在UI線程上加載The task instance must be created on the UI thread. task實例也必須在UI線程中創建execute(Params...)must be invoked on the UI thread. execute()也必須在UI線程上Do not callonPreExecute(),onPostExecute(Result),doInBackground(Params...),onProgressUpdate(Progress...)manually.這幾個方法不能手動調用,就像onCreate一樣

The task can be executed only once (an exception will be thrown if a second execution is attempted(嘗試).) 該任務只能被執行一次,第二次嘗試執行會有拋出異常

 

 

 
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved