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. hihocoder 1523:数组重排2

    题目链接 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定一个1-N的排列A1, A2, ... AN,每次操作小Hi可以选择一个数,把它放到数组的最左边. 请计算小 ...

  2. Jackson工具类使用及配置指南、高性能配置(转)

    Jackson使用工具类 通常,我们对JSON格式的数据,只会进行解析和封装两种,也就是JSON字符串--->Java对象以及Java对象--->JSON字符串. public class ...

  3. 虚拟机安装Linux过程和踩坑

    由于想学习node,服务器端大都使用Linux系统,所以就想着在笔记本上弄个虚拟机,装上Linux,使用xshell在window上操作也方便,也借此来熟悉一下Linux,接下来就解释下安装的步骤和遇 ...

  4. Oracle sql"NOT IN"语句优化,查询A表有、B表没有的数据

    记录量大的情况下,采用NOT IN查询,那肯定会慢的无法接受.比如: SELECT A.* FROM TABLE_A WHERE A.USER_ID NOT IN (SELECT B.USER_ID ...

  5. 探索并发编程(六)------Java多线程性能优化

    大家使用多线程无非是为了提高性能,但如果多线程使用不当,不但性能提升不明显,而且会使得资源消耗更大.下面列举一下可能会造成多线程性能问题的点: 死锁 过多串行化 过多锁竞争 切换上下文 内存同步 下面 ...

  6. Python操作dict时避免出现KeyError的几种方法

    见原文:https://www.polarxiong.com/archives/Python-%E6%93%8D%E4%BD%9Cdict%E6%97%B6%E9%81%BF%E5%85%8D%E5% ...

  7. SQL INNER JOIN

    A INNER JOIN command is queries that combine data from more than 1 table.For two tables that want to ...

  8. 【Python】Django CSRF问题

    参考资料: Django Ajax CSRF 认证:http://www.ziqiangxuetang.com/django/django-csrf.html Python Post遇到csrftok ...

  9. dTree无限级文件夹树和JQuery同步Ajax请求

    曾经都是用JQuery对树的支持来实现文件夹树的,近来闲来无事就弄了下dTree,感觉其无限级文件夹还是挺好的,并且它的使用也比較方便,基本上就是先把要用的js文件即dtree.js和css文件dtr ...

  10. ambari 大数据安装利器

    https://www.ibm.com/developerworks/cn/opensource/os-cn-bigdata-ambari/