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 usepublishProgressto publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdatestep.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.
executemust be invoked on the UI thread.- Do not call
onPreExecute(),onPostExecute,doInBackground,onProgressUpdatemanually. - 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 ...
随机推荐
- Codeforces Beta Round #4 (Div. 2 Only) A. Watermelon 水题
A. Watermelon 题目连接: http://www.codeforces.com/contest/4/problem/A Description One hot summer day Pet ...
- ROS知识(1)----ROS Jade安装
ROS入门难,进去之后会是很简单,这是很多人的经验.但是今天安装ROS就吃了闭门羹,安装成功后,回顾发现,关键是操作系统Ubantu14.04没有安装好,一些系统包没有及时更新导致的.这里总结下ROS ...
- tomcat使用Eclipse进行远程调试(线上调试)
什么是远程调试,就是在A机器上利用Eclipse单步跟踪调试B机器上的Web应用,当然调试A机器上Web应用也是没有问题的,90%我都是调试本机的Web应用,远程调试的意义我想我不用说了,大家都会想到 ...
- CentOS 6.9通过RPM安装EPEL源(http://dl.fedoraproject.org)
另类的装法,通过RPM包直接安装 wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm & ...
- HTML5项目笔记4:使用Audio API设计绚丽的HTML5音乐播放器
HTML5 有两个很炫的元素,就是Audio和 Video,可以用他们在页面上创建音频播放器和视频播放器,制作一些效果很不错的应用. 无论是视屏还是音频,都是一个容器文件,包含了一些音频轨道,视频轨道 ...
- win10怎么彻底关闭自动更新
原文:https://jingyan.baidu.com/article/9faa7231e7b78b473c28cbb6.html 方法/步骤 1 单击左下角开始菜单点击设置图标进入设置界面 2 ...
- 根据url下载图片和页面
需要将&tp=webp&wxfrom=5去掉,既可以在任何地方显示,也可以下载了 http://mmbiz.qpic.cn/mmbiz_jpg/bf8pC39RBhGFOH1ib9Ac ...
- Centos7安装配置tomcat 9并设置自动启动
原文:https://blog.csdn.net/stinkstone/article/details/78082725 1.官网下载安装包 这里选择适合Linux的安装包,下载到本地后上传到cent ...
- unix简史及应用
Unix 简史 1965年时,贝尔实验室(Bell Labs)加入一项由奇异电子(General Electric)和麻省理工学院(MIT)合作的计画:该计画要建立一套多使用者.多任务.多层次(mul ...
- Python实现MapReduce,wordcount实例,MapReduce实现两表的Join
Python实现MapReduce 下面使用mapreduce模式实现了一个简单的统计日志中单词出现次数的程序: from functools import reduce from multiproc ...