安卓實訓第七天---多線程下載實現(進度條)

來源:互聯網
上載者:User

標籤:size   txt   長度   input   access   結束   out   儲存   不可用   

 
 
 
 
 
 
 
 
 
packagecom.example.download;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;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.os.Handler;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {// 定義正在執行的線程private int threadRunning = 3;// 線程開啟的數量private int threadNum = 3;private EditText et_url;// 進度條private ProgressBar progressBar;private TextView tv_pb;private int currentProgress = 0;private boolean flag = true;// 記錄進度條的值public static int pb_count = 0;public static Handler handler;public static final int TEXTVALUE = 1;public static int pb_num = 0;public static int size = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 擷取控制項對象et_url = (EditText) findViewById(R.id.et_url);progressBar = (ProgressBar) findViewById(R.id.tv_jindu);tv_pb = (TextView) findViewById(R.id.tv_pb);File sdDir = Environment.getExternalStorageDirectory();File pdFile = new File(sdDir, "pb.txt");InputStream is = null;try {if (pdFile.exists()) {is = new FileInputStream(pdFile);}} catch (FileNotFoundException e) {e.printStackTrace();}if (is != null) {String value = StreamTools.streamTostr(is);String arr[] = value.split(";");progressBar.setMax(Integer.valueOf(arr[0]));// 最大值currentProgress = Integer.valueOf(arr[1]);// 當前值progressBar.setProgress(currentProgress);;tv_pb.setText("當前的進度是" + arr[2] + "%");}}public void downLoadFile(View v) {// 訪問地址:final String spec = et_url.getText().toString();// "http://172.16.237.144:8080/Login/football.jpg";if (TextUtils.isEmpty(spec)) {Toast.makeText(this, "不可為空", Toast.LENGTH_LONG).show();} else {new Thread() {public void run() {try {URL url = new URL(spec);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// 佈建要求的標頭檔資訊還有時間httpURLConnection.setRequestMethod("GET");httpURLConnection.setConnectTimeout(5000);httpURLConnection.setReadTimeout(5000);if (httpURLConnection.getResponseCode() == 200) {int fileLength = httpURLConnection.getContentLength();// 設定進度條的最大值progressBar.setMax(fileLength);// 推斷你的裝置SDCard是否可用if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 外部存放裝置的路徑File sdfile = Environment.getExternalStorageDirectory();// 擷取檔案的名稱String fileName = spec.substring(spec.lastIndexOf("/") + 1);// 建立儲存的檔案File file = new File(sdfile, fileName);// 建立隨機能夠訪問的檔案對象RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");// 設定檔案大小accessFile.setLength(fileLength);// 關閉操作accessFile.close();// 首先計算出每一個線程下載的大小 開始位置 結束位置int threadSize = fileLength / threadNum;// for迴圈開啟線程處理for (int threadId = 1; threadId <= 3; threadId++) {int startIndex = (threadId - 1)* threadSize;// 開始位置int endIndex = threadId * threadSize - 1;if (threadId == threadNum) {// 最後一個線程endIndex = fileLength - 1;}System.out.println("當前線程--" + threadId+ "開始位置---" + startIndex+ "結束位置---" + endIndex + "線程大小---");// 開啟線程下載要用Start方法new DownLoadThread(threadId, startIndex,endIndex, spec, fileName).start();}} else {MainActivity.this.runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this,"裝置的SD卡不可用", Toast.LENGTH_LONG).show();}});}} else {// 這裡用這個能夠讓它在主線程中執行MainActivity.this.runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this,"server端返回錯誤", Toast.LENGTH_LONG).show();}});}} catch (Exception e) {e.printStackTrace();}};}.start();}}class DownLoadThread extends Thread {private int threadId;private int startIndex;private int endIndex;private String path;private String fileName;public DownLoadThread(int threadId, int startIndex, int endIndex,String path, String fileName) {super();this.threadId = threadId;this.startIndex = startIndex;this.endIndex = endIndex;this.path = path;this.fileName = fileName;}@Overridepublic void run() {// 能夠通過每一個線程去下載檔案了。try {File sdfile = Environment.getExternalStorageDirectory();// 擷取每一個線程下載的記錄檔案File recordFile = new File(sdfile, threadId + ".txt");// 推斷記錄檔案是否存在if (recordFile.exists()) {// 讀取檔案的內容InputStream is = new FileInputStream(recordFile);// 利用工具類轉換String value = StreamTools.streamTostr(is);// 擷取記錄位置int recordIndex = Integer.parseInt(value);// 記錄的位置複製給開始的位置就可以startIndex = recordIndex;}// 通過path路徑構建URL對象URL url = new URL(path);// 通過URL對象的開啟串連,返回對象HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// 佈建要求頭httpURLConnection.setRequestMethod("GET");httpURLConnection.setConnectTimeout(5000);// 設定下載檔案的開始位置和結束位置httpURLConnection.setRequestProperty("Range", "bytes="+ startIndex + "-" + endIndex);// 擷取的狀態嗎int code = httpURLConnection.getResponseCode();if (code == 206) {// 擷取每一個線程返回的流對象:InputStream inputStream = httpURLConnection.getInputStream();// 擷取檔案名稱 由於已經通過那邊傳過來了// String fileName =// path.substring(path.lastIndexOf("/")+1);// 外部存放裝置的路徑File file = new File(sdfile, fileName);// 依據檔案建立她RandomAccessFile對象RandomAccessFile raf = new RandomAccessFile(file, "rwd");raf.seek(startIndex);// 定義讀取的長度int len = 0;byte buffer[] = new byte[50];int total = 0;// 迴圈讀取while ((len = inputStream.read(buffer)) != -1) {System.out.println("當前線程--" + threadId + "--已經下載了"+ (startIndex + total));// 建立線程下載記錄的檔案RandomAccessFile threadfile = new RandomAccessFile(new File(sdfile, threadId + ".txt"), "rwd");threadfile.writeBytes((startIndex + total) + "");threadfile.close();raf.write(buffer, 0, len);total += len;synchronized (MainActivity.this) {currentProgress += len;progressBar.setProgress(currentProgress);// 計算百分比的操作 intfinal String percent = currentProgress * 100L/ progressBar.getMax() + "";MainActivity.this.runOnUiThread(new Runnable() {@Overridepublic void run() {tv_pb.setText("當前的進度是:" + percent + "%");}});RandomAccessFile pbfile = new RandomAccessFile(new File(sdfile, "pb.txt"), "rwd");pbfile.writeBytes(progressBar.getMax() + ";"+ currentProgress + ";" + percent);pbfile.close();}}raf.close();inputStream.close();MainActivity.this.runOnUiThread(new Runnable() {@Overridepublic void run() {// System.out.println("當前線程----"+threadId+"完成下載");Toast.makeText(MainActivity.this,"當前線程----" + threadId + "完成下載",Toast.LENGTH_LONG).show();}});deleteRecordFiles();} else {MainActivity.this.runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "server端下載錯誤",Toast.LENGTH_LONG).show();}});}} catch (Exception e) {e.printStackTrace();}}}public synchronized void deleteRecordFiles() {File sdfile = Environment.getExternalStorageDirectory();System.out.println("-------------------------");threadRunning--;if (threadRunning == 0) {for (int i = 1; i <= 3; i++) {File recordFile = new File(sdfile, i + ".txt");if (recordFile.exists()) {boolean flag1 = recordFile.delete();// 刪除掉檔案System.out.println("下載記錄" + i + "檔案已" + flag1 + "刪除");}File pdFile = new File(sdfile, "pb.txt");if (pdFile.exists()) {boolean flag2 = pdFile.delete();System.out.println("進度條記錄檔案已" + flag2 + "刪除");}}}}public void displayMsg() {}}


BUG注意事項:

1、繼續線程下載的檔案一定要運行threadfile.close(),不然就無法運行後面的刪除TXT檔案部分。

2、一定要注意下載速度的設定,不能太快。超過傳輸檔案的大小。不然會導致模擬器死掉。;

安卓實訓第七天---多線程下載實現(進度條)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.