zoe*_*oey 9 android android-asynctask
每个函数中的"......"是什么意思?为什么在最后一个函数中,没有"......"?
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");
}
}
Run Code Online (Sandbox Code Playgroud)
Nat*_*ate 13
正如Morrison所说,...语法是针对可变长度的参数列表(urls包含多个参数URL).
这通常用于允许用户AsyncTask执行(在您的情况下)传递多个URL以在后台获取.如果您只有一个网址,则可以使用以下网址DownloadFilesTask:
DownloadFilesTask worker = new DownloadFilesTask();
worker.execute(new URL("http://google.com"));
Run Code Online (Sandbox Code Playgroud)
或者使用多个URL,执行以下操作:
worker.execute(new URL[]{ new URL("http://google.com"),
new URL("http://stackoverflow.com") });
Run Code Online (Sandbox Code Playgroud)
本onProgressUpdate()是用来让后台任务交流项目进程的UI.由于后台任务可能涉及多个作业(每个URL参数一个),因此为每个任务发布单独的进度值(例如0到100%完成)可能是有意义的.你不必.您的后台任务当然可以选择计算总进度值,并将该单个值传递给onProgressUpdate().
该onPostExecute()方法是有点不同.它处理从中完成的一组操作中的单个结果doInBackground().例如,如果您下载多个URL,那么如果其中任何一个失败,您可能会返回失败代码.输入参数,以onPostExecute()将您的任何值返回的doInBackground().这就是为什么,在这种情况下,它们都是Long价值观.
如果doInBackground()返回totalSize,那么将传递该值onPostExecute(),其中它可用于通知用户发生了什么,或者您喜欢的任何其他后处理.
如果您确实需要根据后台任务传达多个结果,则可以将Long泛型参数更改为除Long(例如某种集合)之外的其他参数.