AsyncTask简单入门

关系:

java.lang.Object
   ↳    android.os.AsyncTask<Params, Progress, Result>

概述:

AsyncTask是Android提供的轻量级异步类;它在后台线程处理耗时的操作然后能够将处理的结果返回给UI线程处理。因为它不涉及到使用Thread和Handler所以简单易用。

使用方法:

首先上一段Android Developer的代码:
 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");
     }
}
//运行方式
//new DownloadFilesTask().execute(url1, url2, url3);
以下我们看一下详细的使用方法。

1.构建一个类继承AsyncTask

须要注意的是AsyncTask的三中泛型类型
        Params 启动任务运行的输入參数,比方HTTP请求的URL。
        Progress 后台任务运行的百分比。
        Result 后台运行任务终于返回的结果,比方String。 

2.至少实现​ doInBackground (Params... params)这种方法

让我们看一下doInBackground这种方法。
protected abstract Result doInBackground (Params... params)
它接收类型为Params的若干參数,然后返回类型为Result的结果。

3.一般还会实现至少一个 onPostExecute (Result result)方法

protected void onPostExecute (Result result)
它在doInBackground之后被运行,參数就是doInBackground返回的结果。

The 4 steps:

1.onPreExecute()

在AsyncTask被execute之前被运行,通常是做一些准备工作

2.doInBackground(Params...)

在onPreExecute()运行完之后运行,后台线程运行耗时操作

3.onProgressUpdate(Progress...)

在UI线程中运行。在 publishProgress(Progress...)被调用之后运行

4.onPostExecute(Result)

在UI线程中运行,在doInBackground()运行之后运行

Tips:

1.AsyncTask须要在UI线程中载入
2.构建AsyncTask的子类须要在UI线程中
3.execute方法须要在UI线程中被调用
4.对于"The 4 steps"中的四个函数不要自己手动去调用
5.每一个task对象仅仅能被execute一次,不然会报异常



原文地址:https://www.cnblogs.com/bhlsheji/p/4253535.html