AsyncTask

AsyncTask是android平台的,对Java se库中Thread的一个封装,融入了android平台特性。

AsyncTask shold ideally be used for shor operations(a few seconds at the most).如果需要更长时间的任务,可使用Executor,ThreadPoolExcutor or FutureTask.

主要用在这种场景:较大的计算工作在后台执行(比如下载图片、解图片),然后将结果更新在UI线程。

3 Types:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }
1. Params, the parameters sent to the task upon execution.

2.Progress,

3.Result,


4 Steps

1.onPreExecute()

2.doInbackground(Params...), pubulishProgress(Progress...)

3.onProgressUpdate(Progress...)

4.onPostExcute(Result)


Rules

1.the AsyncTask class must be loaded on the UI thread.

2.The Task instance must be created on the UI thread.

3.execute(Params...)must be invoked on the UI thread

4.execute(Parames ...) just can be invoked once.


e.g.

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

你可能感兴趣的:(AsyncTask)