android多線程斷點下載,帶進度條和百分比顯示,斷點下載的臨時數(shù)據(jù)保存到SD卡的文本文檔中,建議可以保存到本地數(shù)據(jù)庫中,這樣可以提高存取效率,從而提高系統(tǒng)性能。
效果:
打開軟件:
下載中:
下載完畢:
附代碼如下:
package com.yy.multiDownloadOfBreakPoint;import java.io.File;import java.io.FileInputStream;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.Handler;import android.os.Message;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;/** * 多線程斷點下載實例 * @author YUANYUAN * */public class MainActivity extends Activity { //下載所使用的線程數(shù) protected static final int threadCount = 3; //下載完畢的標(biāo)記 public static final int downloadOver = 1; //更新下載進度標(biāo)記 public static final int UPDATE_PROGRESS = 0; //下載資源的路徑輸入框 private EditText et_path; //下載的進度條 private ProgressBar pb; //進度顯示 private TextView tv_pb; //當(dāng)前累計下載的數(shù)據(jù) int curDownCount=0; //當(dāng)前活動的下載線程數(shù) protected static int activeThread; //加入消息處理機制 private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case downloadOver: Toast.makeText(MainActivity.this, "文件已下載完畢!", Toast.LENGTH_LONG).show(); tv_pb.setText("下載完成"); break; case UPDATE_PROGRESS: //更新進度顯示 tv_pb.setText("當(dāng)前進度:"+(pb.getProgress()*100/pb.getMax())+"%"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_path=(EditText) findViewById(R.id.et_path); et_path.setText("http://192.168.2.114:8080/sqlite.exe"); pb=(ProgressBar) findViewById(R.id.pb); tv_pb=(TextView) findViewById(R.id.tv_pb); } /** * 開始下載 * @param view */ public void down(View view){ //獲取下載資源的路徑 final String path=et_path.getText().toString().trim(); //判斷資源路徑是否為空 if (TextUtils.isEmpty(path)) { Toast.makeText(this, "請輸入下載資源的路徑", Toast.LENGTH_LONG).show(); return; } //開啟一個線程進行下載 new Thread(){ public void run() { try { //構(gòu)造URL地址 URL url=new URL(path); //打開連接 HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //設(shè)置請求超時的時間 conn.setConnectTimeout(5000); //設(shè)置請求方式 conn.setRequestMethod("GET"); //獲取相應(yīng)碼 int code=conn.getResponseCode(); if (code==200) {//請求成功 //獲取請求數(shù)據(jù)的長度 int length=conn.getContentLength(); //設(shè)置進度條的最大值 pb.setMax(length); //在客戶端創(chuàng)建一個跟服務(wù)器文件大小相同的臨時文件 RandomAccessFile raf=new RandomAccessFile("sdcard/setup.exe", "rwd"); //指定臨時文件的長度 raf.setLength(length); raf.close(); //假設(shè)3個線程去下載資源 //平均每一個線程要下載的文件的大小 int blockSize=length/threadCount; for (int threadId = 1; threadId <= threadCount; threadId++) { //當(dāng)前線程下載數(shù)據(jù)的開始位置 int startIndex=blockSize*(threadId-1); //當(dāng)前線程下載數(shù)據(jù)的結(jié)束位置 int endIndex=blockSize*threadId-1; //確定最后一個線程要下載數(shù)據(jù)的最大位置 if (threadId==threadCount) { endIndex=length; } //顯示下載數(shù)據(jù)的區(qū)間 System.out.println("線程【"+threadId+"】開始下載:"+startIndex+"---->"+endIndex); //開啟下載的子線程 new DownloadThread(path, threadId, startIndex, endIndex).start(); //當(dāng)前下載活動的線程數(shù)加1 activeThread++; System.out.println("當(dāng)前活動的線程數(shù):"+activeThread); } }else{//請求失敗 System.out.println("服務(wù)器異常,下載失敗!"); } } catch (Exception e) { e.printStackTrace(); System.out.println("服務(wù)器異常,下載失敗!"); } }; }.start(); } /** * 下載文件的子線程 每一個文件都下載對應(yīng)的數(shù)據(jù) * @author YUANYUAN * */ public class DownloadThread extends Thread{ private String path; private int threadId; private int startIndex; private int endIndex; /** * 構(gòu)造方法 * @param path 下載文件的路徑 * @param threadId 下載文件的線程 * @param startIndex 下載文件開始的位置 * @param endIndex 下載文件結(jié)束的位置 */ public DownloadThread(String path, int threadId, int startIndex, int endIndex) { this.path = path; this.threadId = threadId; this.startIndex = startIndex; this.endIndex = endIndex; } @Override public void run() { //構(gòu)造URL地址 try { File tempFile=new File("sdcard/"+threadId+".txt"); //檢查記錄是否存在,如果存在讀取數(shù)據(jù),設(shè)置真實下載開始的位置 if (tempFile.exists()) { FileInputStream fis=new FileInputStream(tempFile); byte[] temp=new byte[1024]; int length=fis.read(temp); //讀取到已經(jīng)下載的位置 int downloadNewIndex=Integer.parseInt(new String(temp, 0, length)); //計算出已經(jīng)下載的數(shù)據(jù)長度 int areadyDown=downloadNewIndex-startIndex; //累加已經(jīng)下載的數(shù)據(jù)量 curDownCount+=areadyDown; //設(shè)置進度條已經(jīng)下載的數(shù)據(jù)量 pb.setProgress(curDownCount); //設(shè)置重新開始下載的開始位置 startIndex=downloadNewIndex; fis.close(); //顯示真實下載數(shù)據(jù)的區(qū)間 System.out.println("線程【"+threadId+"】真實開始下載數(shù)據(jù)區(qū)間:"+startIndex+"---->"+endIndex); } URL url = new URL(path); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //設(shè)置請求屬性,請求部分資源 conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); int code=conn.getResponseCode(); if (code==206) {//下載部分資源,正常返回的狀態(tài)碼為206 InputStream is=conn.getInputStream();//已經(jīng)設(shè)置了請求的位置,所以返回的是對應(yīng)的部分資源 //構(gòu)建隨機訪問文件 RandomAccessFile raf=new RandomAccessFile("sdcard/setup.exe", "rwd"); //設(shè)置 每一個線程隨機寫文件開始的位置 raf.seek(startIndex); //開始寫文件 int len=0; byte[] buffer=new byte[1024]; //該線程已經(jīng)下載數(shù)據(jù)的長度 int total=0; while((len=is.read(buffer))!=-1){//讀取輸入流 //記錄當(dāng)前線程已下載數(shù)據(jù)的長度 RandomAccessFile file=new RandomAccessFile("sdcard/"+threadId+".txt","rwd"); raf.write(buffer,0,len);//寫文件 total+=len;//更新該線程已下載數(shù)據(jù)的總長度 System.out.println("線程【"+threadId+"】已下載數(shù)據(jù):"+(total+startIndex)); //將已下載數(shù)據(jù)的位置記錄寫入到文件 file.write((startIndex+total+"").getBytes()); //累加已經(jīng)下載的數(shù)據(jù)量 curDownCount+=len; //更新進度條【進度條的更新可以在非UI線程直接更新,具體見底層源代碼】 pb.setProgress(curDownCount); //更新下載進度 Message msg=Message.obtain(); msg.what=UPDATE_PROGRESS; handler.sendMessage(msg); file.close(); } is.close(); raf.close(); //提示下載完畢 System.out.println("線程【"+threadId+"】下載完畢"); } } catch (Exception e) { e.printStackTrace(); System.out.println("線程【"+threadId+"】下載出現(xiàn)異常??!"); }finally{ //活動的線程數(shù)減少 activeThread--; if (activeThread==0) { for (int i = 1; i <= threadCount; i++) { File tempFile=new File("sdcard/"+i+".txt"); tempFile.delete(); } System.out.println("下載完畢,已清除全部臨時文件"); //界面消息提示下載完畢 Message msg=new Message(); msg.what=downloadOver; handler.sendMessage(msg); } } } }}
以上這篇android多線程斷點下載-帶進度條和百分比進度顯示效果就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選