(Android小應用)在Android中實現多線程斷點下載(連載一)

來源:互聯網
上載者:User

當我們從Internet中下載一個檔案時,有的檔案比較大,比如音樂或視頻檔案,下載的話需要比較長的時間,當我們在下載過程中,如果手機沒電了或者其它原因,使當前的下載中斷了,按照一般的程式,當下次下載又需要從新開始,這裡我們來實現多純程斷點下載,當下載中斷了,下次啟動的時候還會接著下載,有點像我們的迅雷了……

首先呢,我們先不急著建Android應用,先建一個Java項目,測試一下下

然後在這個項目裡面建一個測試案例

包都可以不填,因為只是測試,不是真正的應用,偷懶了……

OK,接著寫代碼

package junit.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.Test;

public class InternetTest {
/**
* 讀取輸入資料流並返回資料
* @param input
* @return
* @throws Exception
*/
public byte[] readStream(InputStream input) throws Exception{
byte[] buffer = new byte[1024];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int len = -1;
while((len=input.read(buffer))!=-1){
output.write(buffer, 0, len);
}
input.close();
output.close();
return output.toByteArray();
}

/**
* 從網路上下載圖片
* @throws Exception
*/

@Test
public void getImage()throws Exception{
String urlPath = "http://photocdn.sohu.com/20110401/Img280097999.jpg";//在網路上隨便找一張圖片的連結
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//返回一個連線物件
conn.setRequestMethod("GET");//佈建要求方式
conn.setConnectTimeout(6*1000);//設定連線逾時,這裡可以不用設定,但是在android應用中應該設定逾時時間
if (conn.getResponseCode()==200) {
InputStream input = conn.getInputStream();
byte[] data = readStream(input);
File file =

相關文章

聯繫我們

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