Android API之android.os.AsyncTask
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:
Params
, the type of the parameters sent to the task upon execution.Progress
, the type of the progress units published during the background computation.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:
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.doInBackground
, invoked on the background thread immediately afteronPreExecute()
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 usepublishProgress
to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate
step.onProgressUpdate
, invoked on the UI thread after a call topublishProgress
. 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.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:
- The task instance must be created on the UI thread.
execute
must be invoked on the UI thread.- Do not call
onPreExecute()
,onPostExecute
,doInBackground
,onProgressUpdate
manually. - The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Android API之android.os.AsyncTask的更多相关文章
- 【Android API】Android 4.1 API官方文档详解
原文:http://android.eoe.cn/topic/summary 翻译:[eoeAndroid原创团队]kris.流风而逝.贼寇在何方.snowxwyo.lsy4833406 更新日期:2 ...
- Android API之android.os.Parcelable
android.os.Parcelable Interface for classes whose instances can be written to and restored from a Pa ...
- Android API之android.content.BroadcastReceiver
android.content.BroadcastReceiver Base class for code that will receive intents sent by sendBroadcas ...
- Android API之android.provider.ContactsContract.RawContacts
android.provider.ContactsContract.RawContacts Constants for the raw contacts table, which contains o ...
- Android API之android.provider.ContactsContract
android.provider.ContactsContract ContactsContract是联系人provider和app的contract.定义了已支持的URL和column.取代了之前的 ...
- Android API之android.widget.Filterable
android.widget.Filterable 定义了一种可过滤的行为.Filterable接口通常有android.widget.Adapter来实现.接口Filterable中有个抽象方法 ...
- Android API之android.content.AsyncQueryHandler
android.content.AsyncQueryHandler A helper class to help make handling asynchronous ContentResolver ...
- Android API之android.provider.ContactsContract.Data
android.provider.ContactsContract.Data Constants for the data table, which contains data points tied ...
- Android API之android.provider.ContactsContract.Contacts
android.provider.ContactsContract.Contacts 对应contacts数据表.RawContacts的一个聚合(aggregate)代表同一个人.每个人在数据表co ...
随机推荐
- HDU 5640 King's Cake GCD
King's Cake 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5640 Description It is the king's birthd ...
- 前端UED网站汇总
爱词霸UED团队 MED | 营销展现研究专家 携程UED-携程旅行前端开发团队 支付宝前端开发车间 Taobao UED Team: 淘宝网用户体验团队博客,有关用户体验设计和研究的经验分享. - ...
- Debian 安装记录
1.蓝色标注是安装的部分或配置的. 作者:http://www.cppblog.com/jinglexy上海体育馆 2.linux 发行版测评网站:www.distrowatch.com 打 ...
- 了解你的Linux系统:必须掌握的20个命令
转载:http://blog.chinaunix.net/uid-16459552-id-3877787.html 要想详细了解你的Linux系统,为系统评估和性能调化提供准确的信息,那么,你会经常用 ...
- Netty Channel 接口名词理解
1.Channel channel 是负责数据读,写的对象,有点类似于老的io里面的stream.它和stream的区别,channel是双向的,既可以write 也可以read,而stream要分o ...
- 神经网络可以拟合任意函数的视觉证明A visual proof that neural nets can compute any function
One of the most striking facts about neural networks is that they can compute any function at all. T ...
- JavaScript 函数大全
javascript函数一共可分为五类: ·常规函数 ·数组函数 ·日期函数 ·数学函数 ·字符串函数 1.常规函数 javascript常规函数包括以下9个函数: (1)alert函数:显示一个警告 ...
- C++中函数调用时的三种参数传递方式详解
在C++中,参数传递的方式是“实虚结合”. 按值传递(pass by value) 地址传递(pass by pointer) 引用传递(pass by reference) 按值传递的过程为:首先计 ...
- Qt 播放音频文件
Qt播放音频文件的方法有好多中,简单介绍几种 不过一下几种方式都需要在Qt工程文件中添加 QT += multimedia 第一 QMediaPlayer类 可以播放MP3文件,同时使用也 ...
- [Python爬虫] 之七:selenium webdriver定位不到元素的五种原因及解决办法(转载)
转载:http://www.51testing.com/html/87/300987-831171.html 1.动态id定位不到元素for example: //WebElement ...