android.os.AsyncTask<Params, Progress, Result>

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.

要点:AsyncTask允许执行后台操作。无需线程、句柄,AsyncTask就可以将结果发布到UI线程。

Usage

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground), and most often will override a second one (onPostExecute.)

要点:AsyncTask必须被扩展。子类至少重写doInBackground方法,通常还会重写onPostExcute方法。

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

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:

并不是所有类型都用到,没用到的可以标记成Void。
 private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread immediately after 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, 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 use publishProgress to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate step.
  3. onProgressUpdate, invoked on the UI thread after a call to publishProgress. 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, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Threading rules

There are a few threading rules that must be followed for this class to work properly:

Android API之android.os.AsyncTask的更多相关文章

  1. 【Android API】Android 4.1 API官方文档详解

    原文:http://android.eoe.cn/topic/summary 翻译:[eoeAndroid原创团队]kris.流风而逝.贼寇在何方.snowxwyo.lsy4833406 更新日期:2 ...

  2. Android API之android.os.Parcelable

    android.os.Parcelable Interface for classes whose instances can be written to and restored from a Pa ...

  3. Android API之android.content.BroadcastReceiver

    android.content.BroadcastReceiver Base class for code that will receive intents sent by sendBroadcas ...

  4. Android API之android.provider.ContactsContract.RawContacts

    android.provider.ContactsContract.RawContacts Constants for the raw contacts table, which contains o ...

  5. Android API之android.provider.ContactsContract

    android.provider.ContactsContract ContactsContract是联系人provider和app的contract.定义了已支持的URL和column.取代了之前的 ...

  6. Android API之android.widget.Filterable

      android.widget.Filterable 定义了一种可过滤的行为.Filterable接口通常有android.widget.Adapter来实现.接口Filterable中有个抽象方法 ...

  7. Android API之android.content.AsyncQueryHandler

    android.content.AsyncQueryHandler A helper class to help make handling asynchronous ContentResolver ...

  8. Android API之android.provider.ContactsContract.Data

    android.provider.ContactsContract.Data Constants for the data table, which contains data points tied ...

  9. Android API之android.provider.ContactsContract.Contacts

    android.provider.ContactsContract.Contacts 对应contacts数据表.RawContacts的一个聚合(aggregate)代表同一个人.每个人在数据表co ...

随机推荐

  1. [转]HorizontalScrollView介绍--支持水平滚动的android布局容器

    类概述 用 于布局的容器,可以放置让用户使用滚动条查看的视图层次结构,允许视图结构比手机的屏幕大.HorizontalScrollView是一种 FrameLayout(框架布局),其子项被滚动查看时 ...

  2. poj 3468 A Simple Problem with Integers 线段树区间加,区间查询和

    A Simple Problem with Integers Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://poj.org/problem?i ...

  3. Scala 元组

    与列表一样,元组也是不可变的,但与列表不同的是元组可以包含不同类型的元素. 元组的值是通过将单个的值包含在圆括号中构成的.例如: val t = (1, 3.14, "Fred") ...

  4. HashMap结构及使用

    HashMap的数据结构 HashMap主要是用数组来存储数据的,我们都知道它会对key进行哈希运算,哈系运算会有重复的哈希值,对于哈希值的冲突,HashMap采用链表来解决的.在HashMap里有这 ...

  5. Scrapy入门教程(转)

    关键字:scrapy 入门教程 爬虫 Spider作者:http://www.cnblogs.com/txw1958/出处:http://www.cnblogs.com/txw1958/archive ...

  6. 2038: [2009国家集训队]小Z的袜子(hose) (莫队算法)

    题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=2038 专题练习: http://acm.hust.edu.cn/vjudge/conte ...

  7. SpringMVC 学习笔记(二) @RequestMapping、@PathVariable等注解

    版权声明:本文为博主原创文章,博客地址:http://blog.csdn.net/a67474506?viewmode=contents 1.1. @RequestMapping映射请求 Spring ...

  8. C# 通过HttpWebRequest在后台对WebService进行调用

    通过HttpWebRequest在后台对WebService进行调用 http://www.cnblogs.com/macroxu-1982/archive/2009/12/23/1630415.ht ...

  9. crtmpserver 在VS2010下的build

    Make sure that you have administrative privileges before doing the following steps.​1. 下载并安装(Microso ...

  10. QMsgPack的用法DEMO

    QMsgPack的用法DEMO 引用单元文件: uses qstring, qmsgpack, qjson; 演示一: procedure TForm2.Button10Click(Sender: T ...