zoukankan      html  css  js  c++  java
  • 【安卓面试题】多线程下载怎么实现?断点续传怎么实现?

    xUTILS插件

    最简单的方法 -- 使用 xUtils的 的HttpUitls下载文件,支持多线程断点下载

    下载地址 https://github.com/wyouflf/xUtils

    使用方法:

    HttpUtils http = new HttpUtils();
    HttpHandler handler = http.download("http://apache.dataguru.cn/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip",
        "/sdcard/httpcomponents-client-4.2.5-src.zip",
        true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
        true, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
        new RequestCallBack<File>() {
    
            @Override
            public void onStart() {
                testTextView.setText("conn...");
            }
    
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                testTextView.setText(current + "/" + total);
            }
    
            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                testTextView.setText("downloaded:" + responseInfo.result.getPath());
            }
    
    
            @Override
            public void onFailure(HttpException error, String msg) {
                testTextView.setText(msg);
            }
    });
    
    ...
    //调用cancel()方法停止下载
    handler.cancel();
    ...
    

    注意 xUtils 已经更新到xUtils3 使用方法也有很多变化。参加官方文档: https://github.com/wyouflf/xUtils3

     

    使用HTTP协议实现多线程断点下载

    多线程实现思路:

    1. 发送http get请求到下载地址
    2. 获取文件总长度,创建和文件等长度的临时文件
    3. 用文件总长度除以线程数,计算每个线程的开始和结束位置
    4. 开启多线程, 按照位置开始下载数据
    5. 将下载数据存在临时文件的对应位置

    加断点

    1. 使用一个int变量记录下载当前总下载长度
    2. 下载时将该变量存入临时文件中
    3. 下次下载以该位置作为下载起点。
    4. 下载完毕后删除临时文件

    详细实现步骤参见: http://blog.csdn.net/guanhang89/article/details/51346790

  • 相关阅读:
    Linked List Cycle leetcode java (链表检测环)
    Remove Duplicates from Sorted List II leetcode java
    Remove Duplicates from Sorted List leetcode java
    Merge Two Sorted Lists leetcode java
    Swap Nodes in Pairs leetcode java
    Median of Two Sorted Array leetcode java
    阿里云最便宜的四种域名注册
    nohup和&后台运行,进程查看及终止
    ipv6转ipv4 NAT64与DNS64基本原理概述
    ros使用pppoe拨号获取ipv6,并且下发IPV6的dns到客户机win7
  • 原文地址:https://www.cnblogs.com/yidan621/p/5669128.html
Copyright © 2011-2022 走看看