"doInBackground(URL... urls)"中的三个点是什么意思?



每个函数中的"…"是什么意思?为什么在最后一个函数中没有"…"?

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");
}
}

正如Morrison所说,...语法用于长度为变量的参数列表(urls包含多个URL)。

这通常用于允许AsyncTask的用户做一些事情,比如(在您的情况下)传入多个要在后台提取的URL。如果你只有一个URL,你会像这样使用DownloadFilesTask

DownloadFilesTask worker = new DownloadFilesTask();
worker.execute(new URL("http://google.com"));   

或者使用多个URL,这样做:

worker.execute(new URL[]{ new URL("http://google.com"), 
new URL("http://stackoverflow.com") });

onProgressUpdate()用于让后台任务向UI传达进度。由于后台任务可能涉及多个作业(每个URL参数一个),因此为每个任务发布单独的进度值(例如,完成0到100%)可能是有意义的。你不必这么做。你的后台任务当然可以选择计算总进度值,并将该单个值传递给onProgressUpdate()

onPostExecute()方法有点不同。它处理来自doInBackground()中完成的一组操作的单个结果。例如,如果您下载了多个URL,那么如果其中任何失败,您可能会返回一个失败代码。onPostExecute()的输入参数将是您doInBackground()返回的任何值。这就是为什么在这种情况下,它们都是Long值。

如果doInBackground()返回totalSize,那么该值将在onPostExecute()上传递,在那里它可以用来通知用户发生了什么,或者您喜欢的任何其他后处理。

如果您的后台任务确实需要传达多个结果,那么您当然可以将Long通用参数更改为Long以外的参数(例如某种集合)。

在Java中,它被称为Varargs,允许可变数量的参数。

http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

这三个点是...,用于表示省略号。在Java语言中,这些点用于表示变量(变量的数量)。

让我来解释一下变容:

变量允许方法接受零或多个论点。如果我们不知道要通过多少争论varargs方法是比较好的方法。

varargs语法:

varargs使用省略号,即数据类型后面的三个点。语法如下:

return_type method_name(data_type... variableName){}

java中变量的简单示例:

class VarargsExample1{  
static void display(String... values){  
System.out.println("display method invoked ");  
}  
public static void main(String args[]){  
display();//zero argument   
display("my","name","is","varargs");//four arguments  
}   
}  

varargs规则:

使用varargs时,必须遵守一些规则,否则程序代码无法编译。规则如下:

方法中只能有一个变量参数。变量自变量(varargs)必须是最后一个自变量。

非常简短(基本)的答案:表示"转换"为数组的可变项目数,它应该是最后一个参数。示例:

test("string", false, 20, 75, 31);
void test(String string, boolean bool, int... integers) {
// string = "string"
// bool = false
// integers[0] = 20
// integers[1] = 75
// integers[2] = 31
}

但你也可以打电话给

test("text", true, 15);

test("wow", true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 123, 345, 9123);

相关内容

最新更新