您好,登錄后才能下訂單哦!
工具類代碼:
package com.example.xiaocool.multithreadclient; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; public class DownUtil { // 定義下載資源的路徑 private String path; // 指定所下載的文件的保存位置 private String targetFile; // 定義需要使用多少線程下載資源 private int threadNum; // 定義下載的線程對象 private DownThread[] threads; // 定義下載的文件的總大小 private int fileSize; public DownUtil(String path, String targetFile, int threadNum) { this.path = path; this.threadNum = threadNum; // 初始化threads數組 threads = new DownThread[threadNum]; this.targetFile = targetFile; } public void download() throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); conn.setRequestProperty( "Accept", "p_w_picpath/gif, p_w_picpath/jpeg, p_w_picpath/pjpeg, p_w_picpath/pjpeg, " + "application/x-shockwave-flash, application/xaml+xml, " + "application/vnd.ms-xpsdocument, application/x-ms-xbap, " + "application/x-ms-application, application/vnd.ms-excel, " + "application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Connection", "Keep-Alive"); // 得到文件大小 fileSize = conn.getContentLength(); conn.disconnect(); int currentPartSize = fileSize / threadNum + 1; RandomAccessFile file = new RandomAccessFile(targetFile, "rw"); // 設置本地文件的大小 file.setLength(fileSize); file.close(); for (int i = 0; i < threadNum; i++) { // 計算每條線程的下載的開始位置 int startPos = i * currentPartSize; // 每個線程使用一個RandomAccessFile進行下載 RandomAccessFile currentPart = new RandomAccessFile(targetFile, "rw"); // 定位該線程的下載位置 currentPart.seek(startPos); // 創建下載線程 threads[i] = new DownThread(startPos, currentPartSize, currentPart); // 啟動下載線程 threads[i].start(); } } // 獲取下載的完成百分比 public double getCompleteRate() { // 統計多條線程已經下載的總大小 int sumSize = 0; for (int i = 0; i < threadNum; i++) { sumSize += threads[i].length; } // 返回已經完成的百分比 return sumSize * 1.0 / fileSize; } private class DownThread extends Thread { // 當前線程的下載位置 private int startPos; // 定義當前線程負責下載的文件大小 private int currentPartSize; // 當前線程需要下載的文件塊 private RandomAccessFile currentPart; // 定義已經該線程已下載的字節數 public int length; public DownThread(int startPos, int currentPartSize, RandomAccessFile currentPart) { this.startPos = startPos; this.currentPartSize = currentPartSize; this.currentPart = currentPart; } @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url .openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); conn.setRequestProperty( "Accept", "p_w_picpath/gif, p_w_picpath/jpeg, p_w_picpath/pjpeg, p_w_picpath/pjpeg, " + "application/x-shockwave-flash, application/xaml+xml, " + "application/vnd.ms-xpsdocument, application/x-ms-xbap, " + "application/x-ms-application, application/vnd.ms-excel, " + "application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("Charset", "UTF-8"); InputStream inStream = conn.getInputStream(); // 跳過startPos個字節,表明該線程只下載自己負責哪部分文件。 inStream.skip(this.startPos); byte[] buffer = new byte[1024]; int hasRead = 0; // 讀取網絡數據,并寫入本地文件 while (length < currentPartSize && (hasRead = inStream.read(buffer)) > 0) { currentPart.write(buffer, 0, hasRead); // 累計該線程下載的總大小 length += hasRead; } currentPart.close(); inStream.close(); } catch (Exception e) { e.printStackTrace(); } } } }
MainActivity:
package com.example.xiaocool.multithreadclient; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends ActionBarActivity { EditText url; EditText target; Button downBn; ProgressBar bar; DownUtil downUtil; private int mDownStatus; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); url = (EditText) findViewById(R.id.url); target = (EditText) findViewById(R.id.target); downBn = (Button) findViewById(R.id.down); bar = (ProgressBar) findViewById(R.id.bar); // 創建一個Handler對象 final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x123) { bar.setProgress(mDownStatus); } } }; downBn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 初始化DownUtil對象 最后一個參數指定線程數 downUtil = new DownUtil(url.getText().toString(), target.getText().toString(), 6); new Thread() { @Override public void run() { try { // 開始下載 downUtil.download(); } catch (Exception e) { e.printStackTrace(); } // 定義美妙調度獲取一次系統的完成進度 final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // 獲取下載任務的完成比例 double completeRate = downUtil.getCompleteRate(); mDownStatus = (int) (completeRate * 100); handler.sendEmptyMessage(0x123); // 下載完成后取消任務調度 if (mDownStatus >= 100) { timer.cancel(); } } }, 0, 100); } }.start(); } }); } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。