我需要在非UI线程和同时运行的UI线程上运行网络进程,以通知用户该进程正在运行,并且该应用程序未被冻结,并赢得&# 39; t允许执行下一个代码块,直到网络连接给出响应。
这样做最好的方法是什么?
答案 0 :(得分:3)
AsyncTasks是要走的路。
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");
}
}