一、AsyncTask
Android封装好的轻量级异步类,使用时候需要实现子类方法
二、线程执行
AsyncTask 允许你在后台线程执行任务并将结果回调到UI线程更新UI相关操作
1. AsyncTask<Params, Progress, Result>
-
Params
: 执行任务发送的参数类型 -
Progress
: 使用后台计算来更新相应的进度 -
Resutlt
: 后台计算的结果类型
public abstract class AsyncTask<Params, Progress, Result> {
...
}
2. 线程执行过程
AsyncTask 是Android上的线程之间进行线程和消息传递
- onPreExecute: 在执行线程之前做根据需要做相应处理(更改UI显示状态)
- doInBackground: 执行后台线程做一些耗时的任务
- publishProgress: 如果想要让后台任务实时进度更新UI 可以调用该方法进行任务进度获取
- doInBackground 执行完毕返回执行的结果调用 OnPostExecute函数执行
屏幕快照 2019-06-29 下午9.08.15.png
3. Android 使用例子
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");
}
}
···
网友评论