安卓的 AsyncTask


Author: yifei / Created: Nov. 15, 2017, 1:05 p.m. / Modified: Nov. 15, 2017, 9:08 p.m. / Edit

asynchronusally run task without explicitly creating thread.

Usage

doInBackground(Params...)
onProgressUpdate(Progress...)
onPostExecute(Result)

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

  Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

template parameters can be Void, Void, Void

see https://developer.android.com/reference/android/os/AsyncTask.html


评论区