1.前言

最近要做一个带进度条下载文件的功能,网上看了一圈,发现好多都是基于 OkHttpClient 添加拦截器来实现的,个人觉得略显复杂,所以还是采用最简单的方法来实现:基于文件写入来进行进度的监听。

2.实现步骤

2.1 设计监听接口

根据需求设计一下接口:

public interface DownloadListener {
  void onStart();//下载开始

  void onProgress(int progress);//下载进度

  void onFinish(String path);//下载完成

  void onFail(String errorInfo);//下载失败
}

如果还需下载速度等等,可以自行设计接口和参数。

2.2 编写网络接口Service

public interface DownloadService {

  @Streaming
  @GET
  Call<ResponseBody> download(@Url String url);
}

跟正常接口写法基本一致,需要注意的是要添加 @Streaming 注解。

默认情况下, Retrofit 在处理结果前会将服务器端的 Response 全部读进内存。如果服务器端返回的是一个非常大的文件,则容易发生oom。使用 @Streaming 的主要作用就是把实时下载的字节就立马写入磁盘,而不用把整个文件读入内存。

2.3 开始网络请求

public class DownloadUtil {

  public static void download(String url, final String path, final DownloadListener downloadListener) {

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.xxx.com")
        //通过线程池获取一个线程,指定callback在子线程中运行。
        .callbackExecutor(Executors.newSingleThreadExecutor())
        .build();

    DownloadService service = retrofit.create(DownloadService.class);

    Call<ResponseBody> call = service.download(url);
    call.enqueue(new Callback<ResponseBody>() {
      @Override
      public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
        //将Response写入到从磁盘中,详见下面分析
        //注意,这个方法是运行在子线程中的
        writeResponseToDisk(path, response, downloadListener);
      }

      @Override
      public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
        downloadListener.onFail("网络错误~");
      }
    });
  }
}

在 Retrofit 中, Callback 默认运行在主线程中,如果我们直接将 Response 写到磁盘这一操作直接运行在主线程中,会报 NetworkOnMainThreadException 异常。所以必须放在子线程中去运行。

目前为止,都还是一个很正常的网络请求。所以,还是很简单的。下面重头戏来了。

2.4 监听下载进度

private static void writeResponseToDisk(String path, Response<ResponseBody> response, DownloadListener downloadListener) {
    //从response获取输入流以及总大小
    writeFileFromIS(new File(path), response.body().byteStream(), response.body().contentLength(), downloadListener);
  }

  private static int sBufferSize = 8192;

  //将输入流写入文件
  private static void writeFileFromIS(File file, InputStream is, long totalLength, DownloadListener downloadListener) {
    //开始下载
    downloadListener.onStart();

    //创建文件
    if (!file.exists()) {
      if (!file.getParentFile().exists())
        file.getParentFile().mkdir();
      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
        downloadListener.onFail("createNewFile IOException");
      }
    }

    OutputStream os = null;
    long currentLength = 0;
    try {
      os = new BufferedOutputStream(new FileOutputStream(file));
      byte data[] = new byte[sBufferSize];
      int len;
      while ((len = is.read(data, 0, sBufferSize)) != -1) {
        os.write(data, 0, len);
        currentLength += len;
        //计算当前下载进度
        downloadListener.onProgress((int) (100 * currentLength / totalLength));
      }
      //下载完成,并返回保存的文件路径
      downloadListener.onFinish(file.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
      downloadListener.onFail("IOException");
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (os != null) {
          os.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

所以,实际就是通过监听文件的写入来实现进度的监听。

2.5 使用例子

String url = "";
      String path = "";
      DownloadUtil.download(url, path, new DownloadListener() {
        @Override
        public void onStart() {
          //运行在子线程
        }

        @Override
        public void onProgress(int progress) {
          //运行在子线程
        }

        @Override
        public void onFinish(String path) {
          //运行在子线程
        }

        @Override
        public void onFail(String errorInfo) {
          //运行在子线程
        }
      });

注意,上面的回调都是运行在子线程中。如果需要更新UI等操作,可以使用Handler等来进行更新。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持悠悠之家。

点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部