多线程断点续传及下载
断点下载
package com.example.downloaddemo;import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.annotation.SuppressLint; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView;public class MoreThreadDownActivity extends Activity implements OnClickListener{private Button start_download1;/** 显示下载进度TextView */ private TextView download_info1;int fileSize;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_more_thread_down);start_download1 = (Button) findViewById(R.id.start_download1);download_info1 = (TextView) findViewById(R.id.download_info1);start_download1.setOnClickListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_more_thread_down, menu);return true;}//点击下载按钮,开始下载 @Overridepublic void onClick(View v) {doDownload();//调用下载的函数 }/** * 使用Handler更新UI界面信息 */ @SuppressLint("HandlerLeak") Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // mProgressbar.setProgress(); // float temp = (float) msg.getData().getInt("size") / (float) fileSize; // int progress = (int) (temp * 100);Log.i("TAG", "当前进度:"+progress); // if (progress == 100) { // Toast.makeText(MainApp.this, "下载完成!", Toast.LENGTH_LONG).show(); // } download_info1.setText("下载进度:" + progress + "%"); } }; /** * 下载准备工作,获取SD卡路径、开启线程 */ private void doDownload() { download_info1.setText("开始下载");// 获取SD卡路径 String path = "/sdcard/" + System.currentTimeMillis() + "acedownload.mp4";String downloadUrl = "http://101.200.142.201:8080/tqyb/ace.mp4";File file = new File(path); // 如果SD卡目录不存在创建 // if (!file.exists()) { // file.mkdir(); // } // 简单起见,我先把URL和文件名称写死,其实这些都可以通过HttpHeader获取到 int threadNum = 5; Log.d("TAG", "download file path:" + path); DownloadTask task = new DownloadTask(downloadUrl, threadNum, path); task.start(); } private static final String TAG = "TAG";/** * 多线程文件下载 * * @author yangxiaolong * @2014-8-7 */ class DownloadTask extends Thread { private String downloadUrl;// 下载链接地址 private int threadNum;// 开启的线程数 private String filePath;// 保存文件路径地址 private int blockSize;// 每一个线程的下载量 public DownloadTask(String downloadUrl, int threadNum, String fileptah) { this.downloadUrl = downloadUrl; this.threadNum = threadNum; this.filePath = fileptah; } @Override public void run() { //创建下载线程的数组,长度为5FileDownloadThread[] threads = new FileDownloadThread[threadNum]; try { URL url = new URL(downloadUrl); //创建下载需要的网络请求对象 URL的对象Log.d(TAG, "download file http path:" + downloadUrl); URLConnection conn = url.openConnection();//创建 网络请求的URLConnection// 读取下载文件总大小 fileSize = conn.getContentLength(); if (fileSize <= 0) { System.out.println("读取文件失败"); return; } // 计算每条线程下载的数据长度 blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum : fileSize / threadNum + 1; Log.d(TAG, "fileSize:" + fileSize + " blockSize:"); //下载的文件,存放的位置File file = new File(filePath); //启动5条线程,同时下载for (int i = 0; i < threads.length; i++) { // 启动线程,分别下载每个线程需要下载的部分 threads[i] = new FileDownloadThread(url, file, blockSize, (i + 1)); threads[i].setName("Thread:" + i); threads[i].start(); } //上面的5条线程,启动后,自己执行自己的,下面的代码也同时执行,不受影响boolean isfinished = false; int downloadedAllSize = 0; while (!isfinished) { //循环判断,5个线程的总体下载进度,已经是否每个都完成了isfinished = true; // 当前所有线程下载总量 downloadedAllSize = 0; for (int i = 0; i < threads.length; i++) { downloadedAllSize += threads[i].getDownloadLength(); if (!threads[i].isCompleted()) { isfinished = false; } } // 通知handler去更新视图组件 Message msg = new Message(); msg.getData().putInt("size", downloadedAllSize); mHandler.sendMessage(msg); // Log.d(TAG, "current downloadSize:" + downloadedAllSize); Thread.sleep(1000);// 休息1秒后再读取下载进度 } Log.d(TAG, " all of downloadSize:" + downloadedAllSize); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.example.downloaddemo;import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.URL; import java.net.URLConnection; import android.util.Log; /** * 文件下载类 * * @author * @2014-5-6 */ public class FileDownloadThread extends Thread { private static final String TAG = FileDownloadThread.class.getSimpleName(); /** 当前下载是否完成 */ private boolean isCompleted = false; /** 当前下载文件长度 */ private int downloadLength = 0; /** 文件保存路径 */ private File file; /** 文件下载路径 */ private URL downloadUrl; /** 当前下载线程ID */ private int threadId; /** 线程下载数据长度 */ private int blockSize; /** * * @param url:文件下载地址 * @param file:文件保存路径 * @param blocksize:下载数据长度 * @param threadId:线程ID */ public FileDownloadThread(URL downloadUrl, File file, int blocksize, int threadId) { this.downloadUrl = downloadUrl; this.file = file; this.threadId = threadId; this.blockSize = blocksize; } @Override public void run() { BufferedInputStream bis = null; RandomAccessFile raf = null; try { URLConnection conn = downloadUrl.openConnection(); conn.setAllowUserInteraction(true); int startPos = blockSize * (threadId - 1);//开始位置 int endPos = blockSize * threadId - 1;//结束位置 //设置当前线程下载的起点、终点 bytes=4-7conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos); System.out.println(Thread.currentThread().getName() + " bytes=" + startPos + "-" + endPos); byte[] buffer = new byte[1024]; bis = new BufferedInputStream(conn.getInputStream()); raf = new RandomAccessFile(file, "rwd"); //创建随机读写流,从本线程下载的位置作为写的位置,把下载的数据写入文件raf.seek(startPos); //设置写的位置int len; while ((len = bis.read(buffer, 0, 1024)) != -1) { //循环读取本次线程下载的数据,写入文件raf.write(buffer, 0, len); downloadLength += len; //记录读取的数据的数量,显示在进度条上 } isCompleted = true; //循环走完了,说明本线程下载完了Log.d(TAG, "current thread task has finished,all size:" + downloadLength); } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (raf != null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 线程文件是否下载完毕 */ public boolean isCompleted() { return isCompleted; } /** * 线程下载文件长度 */ public int getDownloadLength() { return downloadLength; } }
断点续传
package com.example.uptoserverdemo;import java.io.File; import java.io.IOException;import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.*; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.event.OnClick;import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.TextView;public class MainActivity extends Activity {private TextView tv;public static final String UP_URL = "http://169.254.109.73:8080/upserver/UploadFileServlet"; // private String filePath = "/storage/sdcard0/1461656337024acedownload.mp4"; // String fileName = "1461656337024acedownload.mp4";private String filePath = "/mnt/sdcard/ace.mp4";String fileName = "ace.mp4";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.tv);ViewUtils.inject(this);}@OnClick(R.id.tv)public void jump(View view){//异步上传文件new MyAsyncTask().execute();}class MyAsyncTask extends AsyncTask<String, Integer, String>{@Overrideprotected String doInBackground(String... params) {String rs = "";String httpUrl = UP_URL+"?fileName="+fileName; HttpPost request = new HttpPost(httpUrl); File file = new File(filePath);//上传文件的配置代码FileEntity entity = new FileEntity(file,"binary/octet-stream"); entity.setContentEncoding("binary/octet-stream"); request.setEntity(entity); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response; try {response = httpClient.execute(request);//如果返回状态为200,获得返回的结果 if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ //图片上传成功 Log.i("TAG","上传成功");HttpEntity rsEntity = response.getEntity();rs = EntityUtils.toString(rsEntity, "utf-8");Log.i("TAG",rs);} } catch (ClientProtocolException e) {// TODO Auto-generated catch block e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();} return rs;} @Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stub super.onPostExecute(result);tv.setText(result);}}}
转载于:https://www.cnblogs.com/1426837364qqcom/p/5436542.html
多线程断点续传及下载相关推荐
- 多线程断点续传后台下载(首发于安卓巴士)
本菜鸟最近在做一个小项目,项目中用到了多线程断点续传的功能,因为是菜鸟嘛,所以在网络上找了很多教程,不过大多教程只给出了源码,注释跟说明实在太少,也许大牛们不需要太多的解释,可是就苦了小菜们了.本着 ...
- 多线程断点续传后台下载
本菜鸟最近在做一个小项目,项目中用到了多线程断点续传的功能,因为是菜鸟嘛,所以在网络上找了很多教程,不过大多教程只给出了源码,注释跟说明实在太少,也许大牛们不需要太多的解释,可是就苦了小菜们了.本着技 ...
- 多线程断点续传下载软件-闪电下载2009
今天终于把毕业设计做完了,题目是多线程断点续传的下载软件,从五月初到现在,日以继夜的工作,真是累啊....下面可以开始写论文了,哈哈...下面贴两张图,以示庆贺.. 源文件:LightDown.rar ...
- android 多线程断点续传下载 三
android 多线程断点续传下载 三 转载于:https://www.cnblogs.com/zhujiabin/p/5660093.html
- 撸了个多线程断点续传下载器,我从中学习到了这些知识(附开源地址)
2020年6月20日 上海张江 感谢看客老爷点进来了,周末闲来无事,想起同事强哥的那句话:"你有没有玩过断点续传?" 当时转念一想,断点续传下载用的确实不少,具体细节嘛,真的没有去 ...
- OkHttp实现多线程断点续传下载,单例模式下多任务下载管理器,一起抛掉sp,sqlite的辅助吧
丨版权说明 :<OkHttp实现多线程断点续传下载,单例模式下多任务下载管理器,一起抛掉sp,sqlite的辅助吧>于当前CSDN博客和乘月网属同一原创,转载请说明出处,谢谢. 最近项目需 ...
- android 多线程断点续传下载
今天跟大家一起分享下android开发中比较难的一个环节,可能很多人看到这个标题就会感觉头很大,的确如果没有良好的编码能力和逻辑思维,这块是很难搞明白的,前面2次总结中已经为大家分享过有关技术的一些基 ...
- android 多文件多线程断点续传下载
今天跟大家一起分享下android开发中比较难的一个环节,可能很多人看到这个标题就会感觉头很大,的确如果没有良好的编码能力和逻辑思维,这块是很难搞明白的,前面2次总结中已经为大家分享过有关技术的一些基 ...
- Android进阶:多线程断点续传下载
今天跟大家一起分享下android开发中比较难的一个环节,可能很多人看到这个标题就会感觉头很大,的确如果没有良好的编码能力和逻辑思维,这块是很难搞明白的. 什么是多线程下载? 多线程下载其实就是迅雷, ...
最新文章
- OpenAI雄心勃勃的机器人计划失败了:强化学习没法用?
- 代码中的输入输出(重定向、文件流C/C++)
- 基于 Quartz 开发企业级任务调度应用--转
- php怎么弄自动填充,ThinkPHP 自动填充(自动完成)详解及实例
- 误执行了rm -fr /*之后,除了跑路还能怎么办?!
- .Net5 WPF快速入门系列教程
- C语言 strlen函数实现
- 《操作系统》——第一章 计算机系统概述
- 验证码_12306验证码很难吗?2020年最新的Python验证码模块开源
- 【我的失败人生】1105感到自己的弱小
- 1004 成绩排名 (20 分)—PAT (Basic Level) Practice (中文)
- 软件测试学习(一)软件测试基础知识
- RAFT共识算法学习
- 阿里CTO王坚:商业进化的四个关键词
- vue实现自定义步骤条
- Linux(redhat)镜像
- redux启示与实践
- html5中字体显示不出来怎么办,手机字体无法正常显示怎么办
- SparkSession
- java获取客户端的IP地址工具类