先学习断点续传热热身,为多线程下载预热;
其实重点就是下载这里;
1,下载范围的设定
urlConnection.setRequestProperty("Range","bytes=" + start + "-" + info.getLength());
2 , 文件移动到指定位置
randomFile.seek(start);
其他的没有难度,很简单;可以使用数据库或者文件作为缓存文件
主要是一个思路;这里简单的记录一下;作为学习记录
- class MyThread extends Thread{
- private FileInfo info = null;
- public MyThread(FileInfo threadInfo) {
- this.info = threadInfo;
- }
- @Override
- public void run() {
- //向数据库添加线程信息
- if(!threadDAO.isExits(info.getUrl())){
- threadDAO.insert(info);
- }
- HttpURLConnection urlConnection = null;
- RandomAccessFile randomFile =null;
- InputStream inputStream = null;
- try {
- URL url = new URL(info.getUrl());
- urlConnection = (HttpURLConnection) url.openConnection();
- urlConnection.setConnectTimeout(3000);
- urlConnection.setRequestMethod("GET");
- //设置下载位置
- int start = info.getStart() + info.getNow();
- urlConnection.setRequestProperty("Range","bytes=" + start + "-" + info.getLength());
- //设置文件写入位置
- File file = new File(DOWNLOAD_PATH,FILE_NAME);
- randomFile = new RandomAccessFile(file, "rwd");
- randomFile.seek(start);
- //向Activity发广播
- Intent intent = new Intent(ACTION_UPDATE);
- finished += info.getNow();
- if (urlConnection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) {
- //获得文件流
- inputStream = urlConnection.getInputStream();
- byte[] buffer = new byte[512];
- int len = -1;
- long time = System.currentTimeMillis();
- while ((len = inputStream.read(buffer))!= -1){
- //写入文件
- randomFile.write(buffer,0,len);
- //把进度发送给Activity
- finished += len;
- //看时间间隔,时间间隔大于500ms再发
- if(System.currentTimeMillis() - time >500){
- time = System.currentTimeMillis();
- intent.putExtra("now",finished *100 /fileInfo.getLength());
- context.sendBroadcast(intent);
- }
- //判断是否是暂停状态
- if(isPause){
- threadDAO.update(info.getUrl(),finished);
- return; //结束循环
- }
- }
- //删除线程信息
- threadDAO.delete(info.getUrl());
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally {//回收工作略
- }
- }
- }
- }