1、设置布局文件:
<LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入下载的文件网络地址" android:id="@+id/et_path" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="开启几个子线程加速下载" android:text="3" android:id="@+id/et_threadCount" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="下载" android:onClick="downLoad" /> </LinearLayout>2、修改代码:
MainActivity.java:
package com.itheima.multithreaddownload; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText et_path; private EditText et_threadCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_path = (EditText) findViewById(R.id.et_path); et_threadCount = (EditText) findViewById(R.id.et_threadCount); } public void downLoad(View view){ final String path = et_path.getText().toString().trim(); String threadCountStr = et_threadCount.getText().toString().trim(); if(TextUtils.isEmpty(path) || TextUtils.isEmpty(threadCountStr)){ Toast.makeText(this, "下载地址或线程个数不能为空", 0).show(); return; }else{ // final int threadCount = Integer.valueOf(threadCountStr); new Thread(){ public void run() { try { // String path = "http://192.168.22.136:8080/sogou.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(3000); int code = conn.getResponseCode(); if(code == 200){ int length = conn.getContentLength(); //1、在客户端创建一个与服务端文件一样大小的文件 RandomAccessFile file = new RandomAccessFile(Environment.getExternalStorageDirectory()+"/temp.exe", "rw"); file.setLength(length); //3、每个子线程下载数据块 ,下载的起始位置和结束位置 int blockSize = length/threadCount; // threadId * blockSize ---- (threadId+1)* blockSize -1 for(int threadId =0; threadId < threadCount; threadId++){ //下载的起始位置和结束位置 int startIndex = threadId * blockSize; int endIndex = 0; if(threadId != (threadCount -1)){ endIndex = (threadId + 1) * blockSize - 1; }else{ endIndex = length-1; } //开启子线程下载数据 new ThreadDownLoader(path, startIndex, endIndex, threadId, threadCount).start(); } }else{ //抛出异常 } } catch (Exception e) { e.printStackTrace(); } }; }.start(); } } } 使用xutils实现多线程下载(重点)导入xutils包