AsyncTask

来源:互联网 发布:徐州花种子淘宝分部 编辑:程序博客网 时间:2024/05/01 20:05
在新线程中更新UI还必须要引入handler,这让代码看上去非常臃肿。
为了解决这一问题,Android在1.5版本引入了android.os.AsyncTask。AsyncTask的特点是任务在主线程之外运行,而回调方法是在主线程中执行,这就有效地避免了使用Handler带来的麻烦。AsyncTask的任务其实最后是在
AsyncTask本身的一个静态线程池变量中被执行的。当然因为线程池变量为静态的,所以所有的AsyncTask实例的任务其实是在同一个线程池中被执行的。AsyncTask本身有一个静态的Handler.
该Handler用无参数的构造函数进行实例化。与UI进行交互的AsyncTask函数接口cancel(),onProgressUpdate(),onPostExecute()最终也是在该Handler上进行调用。为了确保UI的线程安全,该Handler必须在UI线程上。因此AsyncTask必须在UI线程上被载入。当然为了安全AsyncTask必须在UI线程上被实例。
public abstract class
AsyncTask
extends Object
java.lang.Object
        android.os.AsyncTask<Params, ProgressResult>
第一个为doInBackground接受的参数,第二个为显示进度的参数,第三个为doInBackground返回和onPostExecute传入的参数。
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).)

Here is an example of subclassing:

 private class DownloadFilesTask extends AsyncTask<URLIntegerLong> {
     protected 
Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls);
             publishProgress(
(int) ((i / (float) count) * 100));
         }
         return 
totalSize;
     }

     protected void onProgressUpdate(
Integer... progress) {
         setProgressPercent(
progress[0]);
     }

     protected void onPostExecute(
Long result) {//这个是doInBackground执行完后调用
         showDialog("Downloaded " + result + " bytes");
     }
 }

 
Once created, a task is executed very simply:
 new DownloadFilesTask().execute(url1, url2, url3);
AsyncTask's generic types
The three types used by an asynchronous task are the following:
   1. Params, the type of the parameters sent to the task upon execution.
   2. Progress, the type of the progress units published during the background computation.
   3. 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 type Void:
 private class MyTask extends AsyncTask<Void, Void, Void> { ... }
There are a few threading rules that must be followed for this class to work properly:
    * The task instance must be created on the UI thread.【只能在UI线程中实例化】
    * execute(Params...) must be invoked on the UI thread.【只能在UI线程中调用execute】why?
    * Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
    * The task can be executed only once (an exception will be thrown if a second execution is attempted.)【只能执行一次,第二次回有问题】



原创粉丝点击