【问题标题】:Trying to understand Androids AsynckTask class试图理解 Android AsyncTask 类
【发布时间】:2015-07-15 22:24:09
【问题描述】:

我正在尝试了解 Google 的 AsynckTask 类示例代码。 上线私有类 DownloadFilesTask extends AsyncTask 我假设 Params 是 URL 类型,Progress 是 integer 类型,Result 是 long 类型。

我不明白下面这行 protected Long doInBackground(URL... urls)

Google 的示例代码:

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

}

【问题讨论】:

  • "我不明白下面的行 protected Long doInBackground(URL... urls)" -- 请更详细地解释你不明白的地方。这是一个 Java 类中的方法声明,恰好使用了a varargs parameter
  • 你指的是 URL 是一个参数列表吗? deitel.com/articles/java_tutorials/20060106/…
  • 我同意。 “返回totalSize”到哪里? doInBackground 返回的值是什么?

标签: android


【解决方案1】:

我不明白以下行 protected Long doInBackground(URL... urls)

这意味着:当您将执行任务时,您可以将任意数量的 url 传递给 AsynckTask.execute() 方法:

new DownloadFilesTask().execute();

new DownloadFilesTask().execute(url);

new DownloadFilesTask().execute(url_1, url_2);

等等……

【讨论】:

    【解决方案2】:

    如果你被(URL... urls)这个参数弄糊涂了,我建议你看this question. 基本上,这意味着可以使用零个或多个URL作为方法的参数。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多