android下多线程多任务下载,及断点续传

使用了一个第三方库:filedownloader

引用

compile 'com.liulishuo.filedownloader:library:1.6.9'
使用:

//下载单个文件
public static void downloadSingleFile(String url, String savePath, Context context, final DownloadCallBack callBack){
        FileDownloader.setup(context);
        if(downloader == null){
            downloader = FileDownloader.getImpl();
        }
        downloader.pauseAll();
        downloader.setMaxNetworkThreadCount(15);
        downloader.create(url)
                .setPath(savePath).setAutoRetryTimes(2)
                .setListener(new FileDownloadLargeFileListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        callBack.onProgress((int)((float)soFarBytes/totalBytes*100),task.getSpeed());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        callBack.onCompleted(task.getTargetFilePath());
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        callBack.onFail(e.toString());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();

    }

    private static int totalNum = 0;
//下载多个文件
public static void downloadMuiltyFiles(final List<String> urls, List<String> savePaths, Context context, final DownloadCallBack callBack){ if(urls == null || savePaths == null || urls.size() == 0 || urls.size() != savePaths.size()){ callBack.onCompleted(""); return; } final List<String> actUrls = new ArrayList<>(); List<String> actPaths = new ArrayList<>(); File file = null; int j = 0; for(String p:savePaths){ file = new File(p); if(!file.exists()){ actUrls.add(urls.get(j)); actPaths.add(p); } j++; } if(actPaths.size() == 0){ callBack.onCompleted(""); return; } FileDownloader.setup(context); totalNum = actUrls.size(); final FileDownloadListener downloadListener = new FileDownloadListener() { @Override protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) { } @Override protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) { } @Override protected void blockComplete(BaseDownloadTask task) { } @Override protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) { } @Override protected void completed(BaseDownloadTask task) { totalNum--;


		//多文件下载时,每下载一个文件,回调一次completed
                if(totalNum <= 0){
                    callBack.onCompleted(task.getTargetFilePath());
                }else{
                    int downNum = actUrls.size()-totalNum;
                    callBack.onNumProgress((int)((float)downNum/actUrls.size()*100),downNum,actUrls.size(),task.getSpeed());
                }
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                callBack.onFail(e.toString());
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        };

        final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener);

        final List<BaseDownloadTask> tasks = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            tasks.add(FileDownloader.getImpl().create(urls.get(i)).setPath(actPaths.get(i)).setTag(i + 1));
        }
       // 由于是队列任务, 这里是我们假设了现在不需要每个任务都回调`FileDownloadListener#progress`, 我们只关系每个任务是否完成, 所以这里这样设置可以很有效的减少ipc.
        queueSet.disableCallbackProgressTimes();
        // 所有任务在下载失败的时候都自动重试一次
        queueSet.setAutoRetryTimes(1);
        queueSet.downloadTogether(tasks);
        queueSet.start();

    }


    public interface DownloadCallBack{

        void onCompleted(String filename);

        void onProgress(int progress, int speed);

        void onNumProgress(int progress, int downNum, int totalNum, int speed);

        void onFail(String error);
    }



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java多线程断点续传下载可以使用Java中的线程池和RandomAccessFile类实现。具体步骤如下: 1. 创建一个线程池,线程数量可以根据需要调整。 ``` ExecutorService executorService = Executors.newFixedThreadPool(threadCount); ``` 2. 获取文件大小和已经下载的字节数,计算出每个线程需要下载的字节数。 ``` URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); long fileSize = connection.getContentLength(); long threadSize = fileSize / threadCount; ``` 3. 创建一个RandomAccessFile对象,指定文件名和读写模式。 ``` RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw"); ``` 4. 为每个线程创建一个DownloadThread对象,指定线程编号、起始位置和结束位置。 ``` for (int i = 0; i < threadCount; i++) { long start = i * threadSize; long end = (i == threadCount - 1) ? fileSize - 1 : start + threadSize - 1; DownloadThread thread = new DownloadThread(fileUrl, randomAccessFile, start, end); executorService.execute(thread); } ``` 5. 在DownloadThread中使用HttpURLConnection下载文件,使用RandomAccessFile写入文件。 ``` URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=" + start + "-" + end); InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { randomAccessFile.write(buffer, 0, length); } inputStream.close(); ``` 6. 在程序关闭时,关闭RandomAccessFile和线程池。 ``` randomAccessFile.close(); executorService.shutdown(); ``` 这样就可以实现Java多线程断点续传下载了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值