android 断点续传如何实现的,Android 断点续传功能的实现

目录

17afae82c008?tdsourcetag=s_pcqq_aiomsg

实现效果

按照惯例,效果奉上

17afae82c008?tdsourcetag=s_pcqq_aiomsg

17afae82c008?tdsourcetag=s_pcqq_aiomsg

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(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

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">

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"/>

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/progress"

android:orientation="horizontal">

android:id="@+id/start"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="开始" />

android:id="@+id/stop"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="停止"/>

主方法 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值