学习了多线程下载,而且可以断点续传的逻辑,线程数量可以自己选择,但是线程数量过多手机就承受不起,导致闪退,好在有断点续传。
步骤写在了代码的注释里。大概就是获取服务器文件的大小,在本地新建一个相同大小的文件用来申请空间,然后将服务器的文件读下来写到申请的文件中去。若开多线程,将文件分块,计算每个线程下载的开始位置和结束位置。若断点传输,则保存断开后下载的位置,下次将此位置赋给开始下载的位置即可。细节见代码。
下面是效果图:
布局文件activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/et_path" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入下载路径" android:text="http://10.173.29.234/test.exe" /> <EditText android:id="@+id/et_threadCount" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入线程数量" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="下载" /> <LinearLayout android:id="@+id/ll_pb" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#455eee" android:orientation="vertical"> </LinearLayout> </LinearLayout> </android.support.constraint.ConstraintLayout>
创建布局文件,用来动态显示每个线程的进度条
layout.xml:
<?xml version="1.0" encoding="utf-8"?> <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" />
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<ProgressBar> 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<ProgressBar>(); } //点击按钮实现下载逻辑 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; } }
在清单文件中添加以下权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/200165/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)