Android 断点续传功能的实现
目录

实现效果
按照惯例,效果奉上

Kapture 2018-12-01 at 16.44.09.gif
前言
日更啊!日更!,上一篇比较划水的给大家分享了一下,在做这个功能时候的一点Java基础,IO流,在这个过程中顺便再讲一下另一个IO流中的RandomAccessFile类,那么今天分享一下。
- OKHttp依赖:使用的是OKhttp来连接网络
- RandomAccessFile 来进行IO的读写
- BroadcastReceiver:用来接受和升级UI的
正文
OKManger
OKManger类中实现了 网络连接方法,下载文件方法,启用线程方法;
public class OkManager { private File rootFile;//文件的路径 private File file;//文件 private long downLoadSize;//下载文件的长度 private final ThreadPoolExecutor executor;// 线程池 private boolean isDown = false; //能否已经下载过了(下载后点击暂停) 默认为false private String name; //名称 private String path;// 下载的网址 private RandomAccessFile raf; // 读取写入IO方法 private long totalSize = 0; private MyThread thread;//线程 private Handler handler;//Handler 方法 private DownLoad.IProgress progress;// 下载进度方法,内部定义的笼统方法 /** * 构造方法 OKhttp * @param path 网络连接路径 * @param progress 升级路径 */ public OkManager(String path, DownLoad.IProgress progress) { this.path = path; this.progress = progress; this.handler = new Handler(); this.name = path.substring(path.lastIndexOf("/") + 1); rootFile = FileUtils.getRootFile(); executor = new ThreadPoolExecutor(5, 5, 50, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3000)); //executor.execute(new MyThread()); } /** * 自己设置线程 */ class MyThread extends Thread { @Override public void run() { super.run(); downLoadFile(); } } /** * 这就是下载方法 */ private void downLoadFile() { try { if (file == null) {//判断能否拥有相应的文件 file = new File(rootFile, name); //很正常的File() 方法 raf = new RandomAccessFile(file, "rwd");//实例化一下我们的RandomAccessFile()方法 } else { downLoadSize = file.length();// 文件的大小 if (raf == null) {//判断读取能否为空 raf = new RandomAccessFile(file, "rwd"); } raf.seek(downLoadSize); } totalSize = getContentLength(path);//获取文件的大小 if (downLoadSize == totalSize) {// 判断能否下载完成 //已经下载完成 return; } OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(path). addHeader("Range", "bytes=" + downLoadSize + "-" + totalSize).build(); Response response = client.newCall(request).execute(); InputStream ins = response.body().byteStream(); //上面的就是简单的OKHttp连接网络,通过输入流进行写入到本地 int len = 0; byte[] by = new byte[1024]; long endTime = System.currentTimeMillis(); while ((len = ins.read(by)) != -1 && isDown) {//假如下载没有出错并且已经开始下载,循环进行以下方法 raf.write(by, 0, len); downLoadSize += len; if (System.currentTimeMillis() - endTime > 1000) { final double dd = downLoadSize / (totalSize * 1.0); DecimalFormat format = new DecimalFormat("#0.00"); String value = format.format((dd * 100)) + "%";//计算百分比 Log.i("tag", "==================" + value); handler.post(new Runnable() {//通过Handler发送消息到UI线程,升级 @Override public void run() { progress.onProgress((int) (dd * 100)); } }); } } response.close();//最后要把response关闭 } catch (Exception e) { e.getMessage(); } } /** * 线程开启方法 */ public void start() { if (thread == null) { thread = new MyThread(); isDown = true; executor.execute(thread); } } /** * 线程中止方法 */ public void stop() { if (thread != null) { isDown = false; executor.remove(thread); thread = null; } } //通过OkhttpClient获取文件的大小 public long getContentLength(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); long length = response.body().contentLength(); response.close(); return length; } public interface IProgress { void onProgress(int progress); }}以上的方法,大家仔细的看一看,这里面有详细的注释,大家主要关注downLoadFile()方法,
FileUtils
public class FileUtils { //判断能否安装SDCard public static boolean isSdOk(){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ return true; } return false; } //创立一个文件夹,用来存放下载的文件 public static File getRootFile(){ File sd = Environment.getExternalStorageDirectory(); File rootFile = new File(sd,"TEMPFILE"); if (!rootFile.exists()){ rootFile.mkdirs(); } return rootFile; }}这个就是文件写入的路径,封装的方法,第一个就是判断能否安装SDCard ,第二个方法创立文件夹,存放下载的文件;
activity_main.xml
布局文件,视图,用了两个按钮和progressBar
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="us.mifeng.downloader.MainActivity"> <ProgressBar android:layout_margin="10dp" android:layout_marginTop="20dp" android:id="@+id/progress" android:layout_width="match_parent" android:layout_height="5dp" style="@android:style/Widget.ProgressBar.Horizontal"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/progress" android:orientation="horizontal"> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始" /> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="中止"/> </LinearLayout></RelativeLayout>主方法 Mainactivity()
public class MainActivity extends AppCompatActivity implements View.OnClickListener, DownLoad.IProgress { private String path = "https://download.alicdn.com/wireless/taobao4android/latest/702757.apk"; //private DownLoad downLoad; private ProgressBar pBar; private OkManager downLoad; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //downLoad = new DownLoad(path,this); downLoad = new OkManager(path,this); initView(); } private void initView() { Button start = (Button) findViewById(R.id.start); Button stop = (Button) findViewById(R.id.stop); pBar = (ProgressBar) findViewById(R.id.progress); pBar.setMax(100); start.setOnClickListener(this); stop.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.start: downLoad.start(); break; case R.id.stop: downLoad.stop(); break; } } //显示进度条 @Override public void onProgress(int progress) { pBar.setProgress(progress); }}很简单就是调用了之前封装的方法,大家好好地看响应的方法即可以了
总结
- 断点续传的关键是断点,所以在制定传输协议的时候要设计好,如上图,我自己设置了一个交互协议,每次下载请求都会带上下载的起始点,这样即可以支持从断点下载了, 其实HTTP里的断点续传也是这个原理,在HTTP的头里有个可选的字段RANGE,表示下载的范围。
- Range : 用于用户端到服务器端的请求,可通过该字段指定下载文件的某一段大小,及其单位。典型的格式如:
Range: bytes=0-499 下载第0-499字节范围的内容
Range: bytes=500-999 下载第500-999字节范围的内容
Range: bytes=-500 下载最后500字节的内容
Range: bytes=500- 下载从第500字节开始到文件结束部分的内容
感谢
这个代码其实是我在Github上面找到的响应的方法,比较简单,所以可以更好的放入项目中,希望大家多去大神github上面star
说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Android 断点续传功能的实现
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Android 断点续传功能的实现