java.lang.object
? android.os.asynctask<params, progress, result>
asynctask是android提供的轻量级异步类;它在后台线程处理耗时的操作然后可以将处理的结果返回给ui线程处理。由于它不涉及到使用thread和handler所以简单易用。
首先上一段android developer的代码:
<code></code>
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));
// escape early if cancel() is called
if (iscancelled()) break;
}
return totalsize;
}
protected void onprogressupdate(integer... progress) {
setprogresspercent(progress[0]);
protected void onpostexecute(long result) {
showdialog("downloaded " + result + " bytes");
}
//执行方式
//new downloadfilestask().execute(url1, url2, url3);
下面我们看一下具体的用法。
需要注意的是asynctask的三中泛型类型
params
启动任务执行的输入参数,比如http请求的url。
progress 后台任务执行的百分比。
result 后台执行任务最终返回的结果,比如string。
让我们看一下doinbackground这个方法。
protected abstract result doinbackground (params... params)
它接收类型为params的若干参数,然后返回类型为result的结果。
protected void onpostexecute (result result)
它在doinbackground之后被执行,参数就是doinbackground返回的结果。
在asynctask被execute之前被执行,一般是做一些准备工作
在onpreexecute()执行完之后执行,后台线程执行耗时操作
在ui线程中执行。在 publishprogress(progress...)被调用之后执行
在ui线程中执行,在doinbackground()执行之后执行
1.asynctask需要在ui线程中加载
2.构建asynctask的子类需要在ui线程中
3.execute方法需要在ui线程中被调用
4.对于"the 4 steps"中的四个函数不要自己手动去调用
5.每个task对象只能被execute一次,不然会报异常