【问题标题】:Android - Best Practice for Downloading Medium - Large Files QuicklyAndroid - 快速下载中大文件的最佳实践
【发布时间】:2015-07-18 05:42:27
【问题描述】:

我需要将几个大的 zip 文件下载到我的应用程序中(每个大约 25mb),但它看起来很慢(5 分钟以上),当我们在 iPad 上测试下载相同的文件时,它的下载速度要快几倍。我考虑过使用 Volley,但似乎 asynctask 最适合大文件(根据我的阅读)。

是否有人对我如何能够更快地下载/写入这些文件有任何建议或想法?

我目前的实现如下所示:

我的 AsyncTask 示例:

@Override
 protected String doInBackground(String... sUrl) {
     InputStream input = null;
     OutputStream output = null;
     HttpURLConnection connection = null;
     try {
         URL url = new URL(sUrl[0]);
         connection = (HttpURLConnection) url.openConnection();
         connection.connect();

         // expect HTTP 200 OK, so we don't mistakenly save error report
         // instead of the file
         if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
             return "Server returned HTTP " + connection.getResponseCode()
                     + " " + connection.getResponseMessage();
         }

         // this will be useful to display download percentage
         // might be -1: server did not report the length
         int fileLength = connection.getContentLength();

         // download the file
         input = connection.getInputStream();
         output = new FileOutputStream("/sdcard/file_name.extension");

         byte data[] = new byte[1024];
         long total = 0;
         int count;
         while ((count = input.read(data)) != -1) {
             // allow canceling with back button
             if (isCancelled()) {
                 input.close();
                 return null;
             }
             total += count;
             // publishing the progress....
             if (fileLength > 0) // only if total length is known
                 publishProgress((int) (total * 100 / fileLength));
             output.write(data, 0, count);
         }
     } catch (Exception e) {
         return e.toString();
     } finally {
         try {
             if (output != null)
                 output.close();
             if (input != null)
                 input.close();
         } catch (IOException ignored) {
         }

         if (connection != null)
             connection.disconnect();
     }
     return null;
 }

【问题讨论】:

    标签: android download android-asynctask


    【解决方案1】:

    AsyncTask 应该只用于相对较短的后台进程(即持续几秒钟的进程)。来自文档:

    AsyncTask 被设计成一个围绕 Thread 和 Handler 的辅助类 并且不构成通用线程框架。异步任务 理想情况下应用于短操作(几秒钟在 大多数。)如果您需要保持线程长时间运行, 强烈建议您使用由 java.util.concurrent 包,例如ExecutorThreadPoolExecutorFutureTask.

    对于长时间操作,您应该使用Service

    服务是一个应用程序组件,代表一个 应用程序希望在不执行长时间运行的操作时 与用户交互或为其他人提供功能 使用的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      相关资源
      最近更新 更多