android_断点续传

依赖

compile 'com.squareup.okhttp3:okhttp:3.9.0'
权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
接口

public interface CallBack {

    void startDownload();

    void pauseDownload();

    void finishDownload();

    void downloadProgress(long progress);
}
下载工具类

public class DownLoadUtils {
    private static final String TAG = "DownloadUtils";
    private static volatile DownLoadUtils instance;
    private final OkHttpClient client;
    private String filePath;
    private File downloadFile;
    private long startPosition;

    private Call call;
    private File file;

    private DownLoadUtils() {
        client = new OkHttpClient();
    }
    private CallBack callback;

    public void setListener(CallBack callback) {
        this.callback = callback;
    }
    /**
     * 初始化下载父路径
     *
     * */
    public void initDownload(String path){
        file = new File(path);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdir();
//        }
//        if (!file.exists()) {
//            file.mkdir();
//        }
        filePath = file.getAbsolutePath();
        Log.e(TAG, "initDownload: " + filePath);
    }
    public static DownLoadUtils getInstance() {
        if (null == instance) {
            synchronized (DownLoadUtils.class) {
                if (instance == null) {
                    instance = new DownLoadUtils();
                }
            }
        }
        return instance;
    }
    public void startDownload(String url){
        if (TextUtils.isEmpty(url)) {
            //url为空直接返回回去
            return;
        }
        if (url.contains(".")) {
            String typeName = url.substring(url.lastIndexOf(".") + 1);
            if (url.contains("/")) {
                String name = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
                String fn = name + "." + typeName;
                //父路径 文件名
                downloadFile = new File(file, fn);
            }
        }
        startPosition = 0;
        if (downloadFile.exists()) {
            startPosition = downloadFile.length();
        }

        Request request = new Request.Builder()
                .addHeader("RANGE", "bytes=" + startPosition + "-")
                .url(url)
                .build();

        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.startDownload();
                ResponseBody body = response.body();
                long totalLength = body.contentLength()+startPosition;
                Log.e(TAG, "totalLength: " + totalLength + "----");
                InputStream is = body.byteStream();
                byte[] buf = new byte[2048];
                int len = 0;
                long totalNum = startPosition;
                while((len = is.read(buf,0,buf.length))!=-1){
                    RandomAccessFile raf = new RandomAccessFile(downloadFile, "rw");
                    raf.seek( totalNum);
                    raf.write(buf,0,len);
                    callback.downloadProgress(totalNum*100/totalLength);
                    totalNum+=len;
                    Log.e(TAG, "startposition "+totalNum+"===" );
                }

                callback.finishDownload();
                body.close();
            }
        });

    }
    public void pauseDownload() {
        callback.pauseDownload();
        if (call != null && call.isExecuted()) {
            call.cancel();
        }
    }

}
MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnStart;
    private Button btnPause;
    private String downloadUrl = "http://dlsw.baidu.com/sw-search-sp/soft/4b/17170/Install_WLMessenger14.0.8117.416.1393467029.exe";
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button) findViewById(R.id.button);
        btnPause = (Button) findViewById(R.id.button2);
        textView = (TextView) findViewById(R.id.textView);
        btnStart.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File storageDirectory = Environment.getExternalStorageDirectory();
            String absolutePath = storageDirectory.getAbsolutePath();
            String path = absolutePath + "/Download/";
            Log.e("---", "下载路径"+path);
            DownLoadUtils.getInstance().initDownload(path);
            DownLoadUtils.getInstance().setListener(new CallBack() {
                @Override
                public void startDownload() {

                }

                @Override
                public void pauseDownload() {

                }

                @Override
                public void finishDownload() {

                }

                @Override
                public void downloadProgress(final long progress) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           // Log.e("0000", "run: "+progress+"" );
                            textView.setText(progress+"");
                        }
                    });
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
                DownLoadUtils.getInstance().startDownload(downloadUrl);
                break;
            case R.id.button2:
                DownLoadUtils.getInstance().pauseDownload();
                break;
        }
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值