首页 > 代码库 > AsyncTask

AsyncTask

 1 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 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 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  }
AsyncTask 可以传入 3个泛型参数。4个操作步骤:
  1. 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.
  2. doInBackground(Params...), 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 usepublishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(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.
  4. 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.

 

1. onPreExecute()
这个方法会在后台任务开始执行之前调用,用于进行一些界面上的初始化操作,比
如显示一个进度条对话框等。
2. doInBackground(Params...)
这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任
务。任务一旦完成就可以通过 return 语句来将任务的执行结果返回,如果 AsyncTask 的
第三个泛型参数指定的是 Void,就可以不返回任务执行结果。注意,在这个方法中是不
可以进行 UI 操作的,如果需要更新 UI 元素,比如说反馈当前任务的执行进度,可以调
用 publishProgress(Progress...)方法来完成。
3. onProgressUpdate(Progress...)
当在后台任务中调用了 publishProgress(Progress...)方法后,这个方法就会很快被调
用,方法中携带的参数就是在后台任务中传递过来的。在这个方法中可以对 UI 进行操
作,利用参数中的数值就可以对界面元素进行相应地更新。
4. onPostExecute(Result)
当后台任务执行完毕并通过 return 语句进行返回时,这个方法就很快会被调用。返
回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些 UI 操作,比如
说提醒任务执行的结果,以及关闭掉进度条对话框等。

AsyncTask