Android开发中使用多线程怎么样实现一个断点续传功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
布局文件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" 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"/>
关于Android开发中使用多线程怎么样实现一个断点续传功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。