Android开发中使用多线程怎么样实现一个断点续传功能
创始人
2024-11-20 03:42:21
0次

布局文件activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>


  

    

    

    

创建布局文件,用来动态显示每个线程的进度条

layout.xml:

<?xml version="1.0" encoding="utf-8"?>

MainActivity.java:

import...;

public class MainActivity extends AppCompatActivity {

  private EditText et_path;
  private EditText et_threadCount;
  private LinearLayout ll_pb;
  private String path;

  private static int runningThread;// 代表正在运行的线程
  private int threadCount;
  private List pbList;//集合存储进度条的引用

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et_path = findViewById(R.id.et_path);
    et_threadCount = findViewById(R.id.et_threadCount);
    ll_pb = findViewById(R.id.ll_pb);
    //添加一个进度条的引用
    pbList = new ArrayList();
  }

  //点击按钮实现下载逻辑
  public void click(View view) {
    //获取下载路径
    path = et_path.getText().toString().trim();
    //获取线程数量
    String threadCounts = et_threadCount.getText().toString().trim();
    //移除以前的进度条添加新的进度条
    ll_pb.removeAllViews();
    threadCount = Integer.parseInt(threadCounts);
    pbList.clear();
    for (int i = 0; i < threadCount; i++) {
      ProgressBar v = (ProgressBar) View.inflate(getApplicationContext(), R.layout.layout, null);

      //把v添加到几何中
      pbList.add(v);

      //动态获取进度条
      ll_pb.addView(v);
    }

    //java逻辑移植
    new Thread() {
      @Override
      public void run() {
        /*************/
        System.out.println("你好");
        try {
          URL url = new URL(path);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
          conn.setConnectTimeout(5000);
          int code = conn.getResponseCode();
          if (code == 200) {
            int length = conn.getContentLength();
            // 把运行线程的数量赋值给runningThread
            runningThread = threadCount;

            System.out.println("length=" + length);
            // 创建一个和服务器的文件一样大小的文件,提前申请空间
            RandomAccessFile randomAccessFile = new RandomAccessFile(getFileName(path), "rw");
            randomAccessFile.setLength(length);
            // 算出每个线程下载的大小
            int blockSize = length / threadCount;
            // 计算每个线程下载的开始位置和结束位置
            for (int i = 0; i < length; i++) {
              int startIndex = i * blockSize;// 开始位置
              int endIndex = (i + 1) * blockSize;// 结束位置
              // 特殊情况就是最后一个线程
              if (i == threadCount - 1) {
                // 说明是最后一个线程
                endIndex = length - 1;
              }
              // 开启线程去服务器下载
              DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i);
              downLoadThread.start();

            }

          }
        } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        /*************/
      }
    }.start();

  }

  private class DownLoadThread extends Thread {
    // 通过构造方法吧每个线程的开始位置和结束位置传进来
    private int startIndex;
    private int endIndex;
    private int threadID;
    private int PbMaxSize;//代表当前下载(进度条)的最大值
    private int pblastPosition;//如果中断过,这是进度条上次的位置

    public DownLoadThread(int startIndex, int endIndex, int threadID) {
      this.startIndex = startIndex;
      this.endIndex = endIndex;
      this.threadID = threadID;

    }

    @Override
    public void run() {
      // 实现去服务器下载文件
      try {
        //计算进度条最大值
        PbMaxSize = endIndex - startIndex;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        // 如果中间断过,接着上次的位置继续下载,聪慧文件中读取上次下载的位置
        File file = new File(getFileName(path) + threadID + ".txt");
        if (file.exists() && file.length() > 0) {
          FileInputStream fis = new FileInputStream(file);
          BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
          String lastPosition = bufr.readLine();
          int lastPosition1 = Integer.parseInt(lastPosition);

          //赋值给进度条位置
          pblastPosition = lastPosition1 - startIndex;
          // 改变一下startIndex的值
          startIndex = lastPosition1 + 1;
          System.out.println("线程id:" + threadID + "真实下载的位置:" + lastPosition + "-------" + endIndex);

          bufr.close();
          fis.close();

        }

        conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
        int code = conn.getResponseCode();
        if (code == 206) {
          // 随机读写文件对象
          RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rw");
          // 每个线程从自己的位置开始写

          raf.seek(startIndex);
          InputStream in = conn.getInputStream();
          // 把数据写到文件中
          int len = -1;
          byte[] buffer = new byte[1024];
          int totle = 0;// 代表当前线程下载的大小
          while ((len = in.read(buffer)) != -1) {
            raf.write(buffer, 0, len);
            totle += len;

            // 实现断点续传就是把当前线程下载的位置保存起来,下次再下载的时候按照上次下载的位置继续下载
            int currentThreadPosition = startIndex + totle;// 存到一个txt文本中
            // 用来存储当前线程当前下载的位置
            RandomAccessFile raff = new RandomAccessFile(getFileName(path) + threadID + ".txt", "rwd");
            raff.write(String.valueOf(currentThreadPosition).getBytes());
            raff.close();

            //设置进度条当前的进度
            pbList.get(threadID).setMax(PbMaxSize);
            pbList.get(threadID).setProgress(pblastPosition + totle);
          }
          raf.close();
          System.out.println("线程ID:" + threadID + "下载完成");
          // 将产生的txt文件删除,每个线程下载完成的具体时间不知道
          synchronized (DownLoadThread.class) {
            runningThread--;
            if (runningThread == 0) {
              //说明线程执行完毕
              for (int i = 0; i < threadCount; i++) {

                File filedel = new File(getFileName(path) + i + ".txt");
                filedel.delete();
              }

            }

          }

        }
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    }
  }

  public String getFileName(String path) {
    int start = path.lastIndexOf("/") + 1;
    String subString = path.substring(start);
    String fileName = "/data/data/com.lgqrlchinese.heima76android_11_mutildownload/" + subString;
    return fileName;

  }
}

在清单文件中添加以下权限

   
   

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...