您的位置:首页 > 其它

what does the three dots in “doInBackground(URL… urls)” mean?

2013-09-11 23:23 495 查看
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");
}
}


As Morrison said, the 
...
 syntax
is for a variable length list of arguments (
urls
 holds
more than one
URL
).

This is typically used to allow users of the 
AsyncTask
 to
do things like (in your case) pass in more than one URL to be fetched in the background. If you only have one URL, you would use your
DownloadFilesTask
 like
this:
DownloadFilesTask worker = new DownloadFilesTask();
worker.execute(new URL("http://google.com"));


or with multiple URLs, do this:
worker.execute(new URL[]{ new URL("http://google.com"),
new URL("http://stackoverflow.com") });


The 
onProgressUpdate()
 is
used to let the background task communicate progress to the UI. Since the background task might involve multiple jobs (one for each URL parameter),
it may make sense to publish separate progress values (e.g. 0 to 100% complete) for each task. You don't have to. Your background task could certainly choose to calculate a total progress
value, and pass that single value to
onProgressUpdate()
.

The 
onPostExecute()
 method
is a little different. It processes a single result, from the set of operations that were done in 
doInBackground()
.
For example, if you download multiple URLs, then you might return a failure code if any of them failed. The input parameter to 
onPostExecute()
 will
be whatever value you return from 
doInBackground()
.
That's why, in this case, they are both 
Long
values.

If 
doInBackground()
 returns 
totalSize
,
then that value will be passed on 
onPostExecute()
,
where it can be used to inform the user what happened, or whatever other post-processing you like.

If you really need to communicate multiple results as a result of your background task, you can certainly change the 
Long
 generic
parameter to something other than a 
Long
 (e.g.
some kind of collection).

From Stackoverflow  http://stackoverflow.com/questions/12665769/what-does-the-three-dots-in-doinbackgroundurl-urls-mean
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: