欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android实现多线程断点续传功能

程序员文章站 2023-11-27 12:59:22
本文实例为大家分享了android实现多线程断点续传的具体代码,供大家参考,具体内容如下 布局:

本文实例为大家分享了android实现多线程断点续传的具体代码,供大家参考,具体内容如下

android实现多线程断点续传功能

布局:

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingbottom="@dimen/activity_vertical_margin"
 android:paddingleft="@dimen/activity_horizontal_margin"
 android:paddingright="@dimen/activity_horizontal_margin"
 android:paddingtop="@dimen/activity_vertical_margin">


 <textview
  android:text="下载进度"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignparenttop="true"
  android:layout_alignparentleft="true"
  android:layout_alignparentstart="true"
  android:layout_margintop="15dp"
  android:id="@+id/tv_progress" />

 <button
  android:text="下载"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@+id/firstbar"
  android:layout_alignparentleft="true"
  android:layout_alignparentstart="true"
  android:layout_margintop="29dp"
  android:id="@+id/bt" />

 <button
  android:text="暂停"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_aligntop="@+id/bt"
  android:layout_torightof="@+id/bt"
  android:layout_toendof="@+id/bt"
  android:layout_marginleft="15dp"
  android:layout_marginstart="15dp"
  android:id="@+id/bt_pause" />

 <button
  android:text="继续"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignbottom="@+id/bt_pause"
  android:layout_torightof="@+id/bt_pause"
  android:layout_toendof="@+id/bt_pause"
  android:layout_marginleft="18dp"
  android:layout_marginstart="18dp"
  android:id="@+id/bt_start" />

 <progressbar
  android:id="@+id/firstbar"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  style="@android:style/widget.progressbar.horizontal"
  android:layout_below="@+id/tv_progress"
  android:layout_alignparentleft="true"
  android:layout_alignparentstart="true"
  android:layout_margintop="21dp" />
</relativelayout>

mainactivity :

import android.os.bundle;
import android.os.environment;
import android.support.v7.app.appcompatactivity;
import android.view.view;
import android.widget.button;
import android.widget.progressbar;
import android.widget.textview;
import android.widget.toast;

import butterknife.bindview;
import butterknife.butterknife;
import butterknife.onclick;


public class mainactivity extends appcompatactivity {
 @bindview(r.id.firstbar)
 progressbar firstbar;
 @bindview(r.id.tv_progress)
 textview tvprogress;
 @bindview(r.id.bt)
 button bt;
 @bindview(r.id.bt_pause)
 button btpause;
 @bindview(r.id.bt_start)
 button btstart;
 //下载地址
 private string loadurl = "http://mirror.aarnet.edu.au/pub/ted-talks/911mothers_2010w-480p.mp4";
 //文件缓存路径
 private string filepath = environment.getexternalstoragedirectory() + "/" + "911mothers.mp4";
 downloadfile downloadfile;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  butterknife.bind(this);
  downloadfile = new downloadfile(this, loadurl, filepath, 3);
  downloadfile.setondownloadlistener(new downloadfile.downloadlistener() {
   @override
   public void getprogress(int progress) {
    tvprogress.settext("当前进度 :" + progress + " %");
    //设置进度条进度
    firstbar.setprogress(progress);
    if (progress==100){
     toast.maketext(mainactivity.this, "下载完成", toast.length_short).show();
    }
   }

   @override
   public void oncomplete() {
    toast.maketext(mainactivity.this, "下载完成", toast.length_short).show();
   }

   @override
   public void onfailure() {
    toast.maketext(mainactivity.this, "下载失败", toast.length_short).show();
   }
  });



 }

 /*
 * 点击事件
 * */
 @onclick({r.id.bt, r.id.bt_pause, r.id.bt_start})
 public void onviewclicked(view view) {
  switch (view.getid()) {
   case r.id.bt:
    downloadfile.download();
    break;
   case r.id.bt_pause:
    downloadfile.onpause();
    break;
   case r.id.bt_start:
    downloadfile.onstart();
    break;
  }
 }

 @override
 protected void ondestroy() {
  downloadfile.ondestroy();
  super.ondestroy();
 }
}

downloadfile:

import android.content.context;
import android.content.sharedpreferences;
import android.os.handler;
import android.os.message;

import java.io.inputstream;
import java.io.randomaccessfile;
import java.net.httpurlconnection;
import java.net.url;

public class downloadfile {
 private static final string sp_name = "download_file";
 private static final string curr_length = "curr_length";
 private static final int default_thread_count = 4;//默认下载线程数

 //以下为线程状态
 private static final string download_init = "1"; //初始化
 private static final string download_ing = "2";  //正在下载
 private static final string download_pause = "3"; //暂停
 private context mcontext;
 private string loadurl;//网络获取的url
 private string filepath;//下载到本地的path
 private int threadcount = default_thread_count;//下载线程数
 private int filelength;//文件总大小
 //使用volatile防止多线程不安全
 private volatile int currlength;//当前总共下载的大小
 private volatile int runningthreadcount;//正在运行的线程数
 private thread[] mthreads;
 private string statedownload = download_init;//当前线程状态

 //下载进度监听
 private downloadlistener mdownloadlistener;

 public void setondownloadlistener(downloadlistener mdownloadlistener) {
  this.mdownloadlistener = mdownloadlistener;
 }

 //定义一个下载监听的接口
 public interface downloadlistener {
  //返回当前下载进度的百分比
  void getprogress(int progress);
  //下载完成
  void oncomplete();
  //下载失败
  void onfailure();
 }

 /*
 * 四种有参构造
 * */
 public downloadfile(context mcontext, string loadurl, string filepath) {
  this(mcontext, loadurl, filepath, default_thread_count, null);
 }

 public downloadfile(context mcontext, string loadurl, string filepath, downloadlistener mdownloadlistener) {
  this(mcontext, loadurl, filepath, default_thread_count, mdownloadlistener);
 }

 public downloadfile(context mcontext, string loadurl, string filepath, int threadcount) {
  this(mcontext, loadurl, filepath, threadcount, null);
 }

 public downloadfile(context mcontext, string loadurl, string filepath, int threadcount, downloadlistener mdownloadlistener) {
  this.mcontext = mcontext;
  this.loadurl = loadurl;
  this.filepath = filepath;
  this.threadcount = threadcount;
  runningthreadcount = 0;
  this.mdownloadlistener = mdownloadlistener;
 }

 /**
  * 开始下载
  */
 protected void download() {
  //在线程中运行,防止anr
  new thread(new runnable() {
   @override
   public void run() {
    try {
     //初始化数据
     if (mthreads == null)
      mthreads = new thread[threadcount];

     //建立连接请求
     url url = new url(loadurl);
     httpurlconnection conn = (httpurlconnection) url.openconnection();
     conn.setconnecttimeout(5000);
     conn.setrequestmethod("get");
     int code = conn.getresponsecode();//获取返回码
     if (code == 200) {//请求成功,根据文件大小开始分多线程下载
      filelength = conn.getcontentlength();
      //根据文件大小,先创建一个空文件
      //“r“——以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 ioexception。
      //“rw“——打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
      //“rws“—— 打开以便读取和写入,对于 “rw”,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
      //“rwd“——打开以便读取和写入,对于 “rw”,还要求对文件内容的每个更新都同步写入到底层存储设备。
      randomaccessfile raf = new randomaccessfile(filepath, "rwd");
      raf.setlength(filelength);
      raf.close();
      //计算各个线程下载的数据段
      int blocklength = filelength / threadcount;

      sharedpreferences sp = mcontext.getsharedpreferences(sp_name, context.mode_private);
      //获取上次取消下载的进度,若没有则返回0
      currlength = sp.getint(curr_length, 0);
      for (int i = 0; i < threadcount; i++) {
       //开始位置,获取上次取消下载的进度,默认返回i*blocklength,即第i个线程开始下载的位置
       int startposition = sp.getint(sp_name + (i + 1), i * blocklength);
       //结束位置,-1是为了防止上一个线程和下一个线程重复下载衔接处数据
       int endposition = (i + 1) * blocklength - 1;
       //将最后一个线程结束位置扩大,防止文件下载不完全,大了不影响,小了文件失效
       if ((i + 1) == threadcount)
        endposition = endposition * 2;

       mthreads[i] = new downthread(i + 1, startposition, endposition);
       mthreads[i].start();
      }
     } else {
      handler.sendemptymessage(failure);
     }
    } catch (exception e) {
     e.printstacktrace();
     handler.sendemptymessage(failure);
    }
   }
  }).start();
 }

 /**
  * 取消下载
  */
 protected void cancel() {
  if (mthreads != null) {
   //若线程处于等待状态,则while循环处于阻塞状态,无法跳出循环,必须先唤醒线程,才能执行取消任务
   if (statedownload.equals(download_pause))
    onstart();
   for (thread dt : mthreads) {
    ((downthread) dt).cancel();
   }
  }
 }

 /**
  * 暂停下载
  */
 protected void onpause() {
  if (mthreads != null)
   statedownload = download_pause;
 }

 /**
  * 继续下载
  */
 protected void onstart() {
  if (mthreads != null)
   synchronized (download_pause) {
    statedownload = download_ing;
    download_pause.notifyall();
   }
 }

 protected void ondestroy() {
  if (mthreads != null)
   mthreads = null;
 }

 private class downthread extends thread {

  private boolean isgoon = true;//是否继续下载
  private int threadid;
  private int startposition;//开始下载点
  private int endposition;//结束下载点
  private int currposition;//当前线程的下载进度

  private downthread(int threadid, int startposition, int endposition) {
   this.threadid = threadid;
   this.startposition = startposition;
   currposition = startposition;
   this.endposition = endposition;
   runningthreadcount++;
  }

  @override
  public void run() {
   sharedpreferences sp = mcontext.getsharedpreferences(sp_name, context.mode_private);
   try {
    url url = new url(loadurl);
    httpurlconnection conn = (httpurlconnection) url.openconnection();
    conn.setrequestmethod("get");
    conn.setrequestproperty("range", "bytes=" + startposition + "-" + endposition);
    conn.setconnecttimeout(5000);
    //若请求头加上range这个参数,则返回状态码为206,而不是200
    if (conn.getresponsecode() == 206) {
     inputstream is = conn.getinputstream();
     randomaccessfile raf = new randomaccessfile(filepath, "rwd");
     raf.seek(startposition);//跳到指定位置开始写数据
     int len;
     byte[] buffer = new byte[1024];
     while ((len = is.read(buffer)) != -1) {
      //是否继续下载
      if (!isgoon)
       break;
      //回调当前进度
      if (mdownloadlistener != null) {
       currlength += len;
       int progress = (int) ((float) currlength / (float) filelength * 100);
       handler.sendemptymessage(progress);
      }

      raf.write(buffer, 0, len);
      //写完后将当前指针后移,为取消下载时保存当前进度做准备
      currposition += len;
      synchronized (download_pause) {
       if (statedownload.equals(download_pause)) {
        download_pause.wait();
       }
      }
     }
     is.close();
     raf.close();
     //线程计数器-1
     runningthreadcount--;
     //若取消下载,则直接返回
     if (!isgoon) {
      //此处采用sharedpreferences保存每个线程的当前进度,和三个线程的总下载进度
      if (currposition < endposition) {
       sp.edit().putint(sp_name + threadid, currposition).apply();
       sp.edit().putint(curr_length, currlength).apply();
      }
      return;
     }
     if (runningthreadcount == 0) {
      sp.edit().clear().apply();
      handler.sendemptymessage(success);
      handler.sendemptymessage(100);
      mthreads = null;
     }
    } else {
     sp.edit().clear().apply();
     handler.sendemptymessage(failure);
    }
   } catch (exception e) {
    sp.edit().clear().apply();
    e.printstacktrace();
    handler.sendemptymessage(failure);
   }
  }

  public void cancel() {
   isgoon = false;
  }
 }

 //请求成功
 private final int success = 0x00000101;
 //请求失败
 private final int failure = 0x00000102;

 private handler handler = new handler() {
  @override
  public void handlemessage(message msg) {

   if (mdownloadlistener != null) {
    if (msg.what == success) {
     mdownloadlistener.oncomplete();
    } else if (msg.what == failure) {

     mdownloadlistener.onfailure();
    } else {
     mdownloadlistener.getprogress(msg.what);
    }
   }
  }
 };
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。