AsyncTask简介
1. AsyncTask提供了一种恰当的简单的跟UI Thread交互的方式。2. 它不需要通过操控Threads或Handler就可以将后台操作以及其结果展示在UI Thread上。
3. AsyncTask是围绕Thread和Handler被设计出的一个Helper类,它不构成一般的线程框架。
4. AsyncTasks使用在短时间操作(最多几秒钟)上是非常理想的。
5. 如果你需要保持一个长时间操作,强烈建议还是使用java.util.concurrent包中的类,比如Executor、ThreadPollExecutor和FutureTask。
如何定义一个Asynchronous Task
1. 需要在后台进行计算2. 结果要被public到UI Thread上。
定义Asynchronous Task的三个元素
1. Params 参数2. Progress 进度
3. Result 结果
定义Asynchronous Task的4个步骤
1. onPreExecute2. doInBackground
3. onProgressUpdate
4. onPostExecute
范例
1. 类的实现
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");
}
}
2. 执行
new DownloadFilesTask().execute(url1, url2, url3);
3. 取消Task
Async Task可以通过cancel(boolean)在任何时间cancel.在cancel之后,isCancelled()返回的函数会变成true。在cancel函数被调用后,onCancelled(Object)会替代onPostExecute(Object)在doInBackground(Object[])之后被调用,
注.如果要尽快确定task被cancelled,要周期性的不断在doInBackground(Object[])检查isCancelled(),
可以在里头内置一个 循环,不断的查询。
4. 使用规则
1. AsyncTask类必须在UI线程中被实例化。2. AsyncTask必须在UI线程中被创建。
3. execute(Params...) 必须在UI线程中被调用
4. 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;
5. task只能被执行一次