Issue
what does the "..." in each function mean? and why in the last function, there is no "..."?
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");
}
}
Solution
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).
Answered By - Nate
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.