目录
实现效果
按照惯例, 效果奉上
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 上面找到的响应的方法, 比较简单, 所以可以更好的放入项目中, 希望大家多去大神 https://github.com/flyingtercel/DownloadFile 上面 star
来源: http://www.jianshu.com/p/17afae82c008