Android進階:實現多線程下載檔案

來源:互聯網
上載者:User

多線程下載大概思路就是通過Range 屬性實現檔案分段,然後用RandomAccessFile 來讀寫檔案,最終合并為一個檔案

 

首先看下

 


 

建立工程 ThreadDemo

 

首先布局檔案 threaddemo.xml

 

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text=""<br /> /><br /><TextView<br />android:id="@+id/downloadurl"<br />android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br />android:lines="5"<br />/><br /><TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="線程數"<br /> /><br /><EditText<br />android:id="@+id/downloadnum"<br />android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br />/><br /><ProgressBar<br />android:id="@+id/downloadProgressBar"<br />android:layout_width="fill_parent"<br />style="?android:attr/progressBarStyleHorizontal"<br /> android:layout_height="wrap_content"<br />/><br /><TextView<br />android:id="@+id/downloadinfo"<br />android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="下載進度 0"<br />/><br /><Button<br />android:id="@+id/downloadbutton"<br />android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:text="開始下載"<br />/><br /></LinearLayout><br />

 

主介面 Acitivity

 

public class ThreadDownloadDemo extends Activity {</p><p>private TextView downloadurl;<br />private EditText downloadnum;<br />private Button downloadbutton;<br />private ProgressBar downloadProgressBar;<br />private TextView downloadinfo;<br />private int downloadedSize = 0;<br />private int fileSize = 0;</p><p>private long downloadtime;</p><p>@Override<br />public void onCreate(Bundle savedInstanceState) {<br />super.onCreate(savedInstanceState);<br />setContentView(R.layout.threaddemo);</p><p>downloadurl = (TextView) findViewById(R.id.downloadurl);<br />downloadurl.setText("http://file16.top100.cn/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3");<br />downloadnum = (EditText) findViewById(R.id.downloadnum);<br />downloadinfo = (TextView) findViewById(R.id.downloadinfo);<br />downloadbutton = (Button) findViewById(R.id.downloadbutton);<br />downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);<br />downloadProgressBar.setVisibility(View.VISIBLE);<br />downloadProgressBar.setMax(100);<br />downloadProgressBar.setProgress(0);<br />downloadbutton.setOnClickListener(new OnClickListener() {<br />public void onClick(View v) {<br />download();<br />downloadtime = SystemClock.currentThreadTimeMillis();<br />}<br />});<br />}</p><p>private void download() {<br />// 擷取SD卡目錄<br />String dowloadDir = Environment.getExternalStorageDirectory()<br />+ "/threaddemodownload/";<br />File file = new File(dowloadDir);<br />//建立下載目錄<br />if (!file.exists()) {<br />file.mkdirs();<br />}</p><p>//讀取下載線程數,如果為空白,則單線程下載<br />int downloadTN = Integer.valueOf("".equals(downloadnum.getText()<br />.toString()) ? "1" : downloadnum.getText().toString());<br />String fileName = "hetang.mp3";<br />//開始下載前把下載按鈕設定為不可用<br />downloadbutton.setClickable(false);<br />//進度條設為0<br />downloadProgressBar.setProgress(0);<br />//開機檔案下載線程<br />new downloadTask("http://file16.top100.cn/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3", Integer<br />.valueOf(downloadTN), dowloadDir + fileName).start();<br />}</p><p>Handler handler = new Handler() {<br />@Override<br />public void handleMessage(Message msg) {<br />//當收到更新視圖訊息時,計算已完成下載百分比,同時更新進度條資訊<br />int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue();<br />if (progress == 100) {<br />downloadbutton.setClickable(true);<br />downloadinfo.setText("下載完成!");<br />Dialog mdialog = new AlertDialog.Builder(ThreadDownloadDemo.this)<br />.setTitle("提示資訊")<br />.setMessage("下載完成,總用時為:"+(SystemClock.currentThreadTimeMillis()-downloadtime)+"毫秒")<br />.setNegativeButton("確定", new DialogInterface.OnClickListener(){<br />@Override<br />public void onClick(DialogInterface dialog, int which) {<br />dialog.dismiss();<br />}<br />})<br />.create();<br />mdialog.show();<br />} else {<br />downloadinfo.setText("當前進度:" + progress + "%");<br />}<br />downloadProgressBar.setProgress(progress);<br />}</p><p>};</p><p>public class downloadTask extends Thread {<br />private int blockSize, downloadSizeMore;<br />private int threadNum = 5;<br />String urlStr, threadNo, fileName;</p><p>public downloadTask(String urlStr, int threadNum, String fileName) {<br />this.urlStr = urlStr;<br />this.threadNum = threadNum;<br />this.fileName = fileName;<br />}</p><p>@Override<br />public void run() {<br />FileDownloadThread[] fds = new FileDownloadThread[threadNum];<br />try {<br />URL url = new URL(urlStr);<br />URLConnection conn = url.openConnection();<br />//防止返回-1<br />InputStream in = conn.getInputStream();<br />//擷取下載檔案的總大小<br />fileSize = conn.getContentLength();<br />Log.i("bb", "======================fileSize:"+fileSize);<br />//計算每個線程要下載的資料量<br />blockSize = fileSize / threadNum;<br />// 解決整除後百分比計算誤差<br />downloadSizeMore = (fileSize % threadNum);<br />File file = new File(fileName);<br />for (int i = 0; i < threadNum; i++) {<br />Log.i("bb", "======================i:"+i);<br />//啟動線程,分別下載自己需要下載的部分<br />FileDownloadThread fdt = new FileDownloadThread(url, file, i * blockSize, (i + 1) * blockSize - 1);<br />fdt.setName("Thread" + i);<br />fdt.start();<br />fds[i] = fdt;<br />}<br />boolean finished = false;<br />while (!finished) {<br />// 先把整除的餘數搞定<br />downloadedSize = downloadSizeMore;<br />finished = true;<br />for (int i = 0; i < fds.length; i++) {<br />downloadedSize += fds[i].getDownloadSize();<br />if (!fds[i].isFinished()) {<br />finished = false;<br />}<br />}<br />handler.sendEmptyMessage(0);<br />//線程暫停一秒<br />sleep(1000);<br />}<br />} catch (Exception e) {<br />e.printStackTrace();<br />}</p><p>}<br />}<br />}

 

這裡啟動線程將檔案分割為幾個部分,每一個部分再啟動一個線程去下載資料

 

下載檔案的線程

 

public class FileDownloadThread extends Thread{<br />private static final int BUFFER_SIZE=1024;<br />private URL url;<br />private File file;<br />private int startPosition;<br />private int endPosition;<br />private int curPosition;<br />//標識當前線程是否下載完成<br />private boolean finished=false;<br />private int downloadSize=0;<br />public FileDownloadThread(URL url,File file,int startPosition,int endPosition){<br />this.url=url;<br />this.file=file;<br />this.startPosition=startPosition;<br />this.curPosition=startPosition;<br />this.endPosition=endPosition;<br />}<br />@Override<br />public void run() {<br /> BufferedInputStream bis = null;<br /> RandomAccessFile fos = null;<br /> byte[] buf = new byte[BUFFER_SIZE];<br /> URLConnection con = null;<br /> try {<br /> con = url.openConnection();<br /> con.setAllowUserInteraction(true);<br /> //設定當前線程下載的起止點<br /> con.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);<br /> Log.i("bb", Thread.currentThread().getName()+" bytes=" + startPosition + "-" + endPosition);<br /> //使用java中的RandomAccessFile 對檔案進行隨機讀寫操作<br /> fos = new RandomAccessFile(file, "rw");<br /> //設定寫檔案的起始位置<br /> fos.seek(startPosition);<br /> bis = new BufferedInputStream(con.getInputStream());<br /> //開始迴圈以流的形式讀寫檔案<br /> while (curPosition < endPosition) {<br /> int len = bis.read(buf, 0, BUFFER_SIZE);<br /> if (len == -1) {<br /> break;<br /> }<br /> fos.write(buf, 0, len);<br /> curPosition = curPosition + len;<br /> if (curPosition > endPosition) {<br /> downloadSize+=len - (curPosition - endPosition) + 1;<br /> } else {<br /> downloadSize+=len;<br /> }<br /> }<br /> //下載完成設為true<br /> this.finished = true;<br /> bis.close();<br /> fos.close();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br />}</p><p>public boolean isFinished(){<br />return finished;<br />}</p><p>public int getDownloadSize() {<br />return downloadSize;<br />}<br />}

 

這裡通過RandomAccessFile 的seek方法定位到相應的位置 並即時記錄下載量

 

當然這裡需要連網和訪問SD卡 所以要加上相應的許可權

 

<uses-permission android:name="android.permission.INTERNET" /><br /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

 

這樣就OK了 下面可以看看斷點續傳的問題了。有待測試~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.