網絡連接2 單線程和多線程下載 並更新progressbar

1,單線程下載     AsyncTask來更新UI 

case R.id.button_download_single:
new DownloadTask().execute();
private class DownloadTask extends AsyncTask<String,Integer,String>{
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressBar.setProgress((int)(values[0]*100.0/values[1]));
}

@Override
protected String doInBackground(String... params) {

try {

// URL url = new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3");
URL url = new URL("http://js.tudouui.com/bin/player2/olc_8.swf");
/**
* 用url.openConnection()獲得URLConnection
*/
URLConnection urlConnection = url.openConnection();
/**
* 獲取總長度,用於設置進度條
*/
int length = urlConnection.getContentLength();
InputStream inputStream = urlConnection.getInputStream();
/**
* 在本地創建文件,別忘了設置寫的權限
*/
File file = new File(Environment.getExternalStorageDirectory(),"aa.mp3");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
byte[] array = new byte[1024];
int sum = 0;
int index = inputStream.read(array);
while (index!=-1){
fos.write(array,0,index);
sum+=index;
publishProgress(sum,length);
index =inputStream.read(array);
}
fos.flush();
fos.close();
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

2,多線程下載 
界面,數據部分
case R.id.button_download_multi:
//多線程下載

new Thread(new Runnable() {
@Override
public void run() {
try {
String urlPath="http://filelx.liqucn.com/upload/2015/jiaotong/didi_psnger_test4_93_v395_94.ptada";
URL url = new URL(urlPath);
URLConnection connection=url.openConnection();
length=connection.getContentLength();
File file=new File(Environment.getExternalStorageDirectory(),"heinika.apk");
if(!file.exists()){
file.createNewFile();
}
MultiThread[] threads=new MultiThread[5];
for (int i=0;i<5;i++){
MultiThread thread=null;
if(i==4){
thread = new MultiThread(length / 5*4, length , urlPath, file.getAbsolutePath());
}else {
thread = new MultiThread(length / 5 * i, length / 5 * (i + 1), urlPath, file.getAbsolutePath());
}
thread.start();
threads[i]=thread;
}
boolean isFinish=false;

while(!isFinish){
int sum=0;
for (MultiThread thread:threads){
sum+= thread.getSum();
}
Message msg= handler.obtainMessage();
msg.what=0x23;
msg.arg1=sum;
handler.sendMessage(msg);
if(sum==length){
isFinish=true;
}
Thread.sleep(1000);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}).start();
break;
接收消息的handler,用來更新UI
int length;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0x23:
mProgressBar.setMax(length);
mProgressBar.setProgress(msg.arg1);
break;
}
}
};
可以下載指定位置的線程
public class MultiThread extends Thread{
public MultiThread(long start, long end, String url, String filePath) {
this.start = start;
this.end = end;
this.urlPath = url;
this.filePath = filePath;
}
private int sum=0;
private long start;
private long end;
private String urlPath;
private String filePath;

public int getSum() {
return sum;
}

@Override
public void run() {
try {
URL url=new URL(urlPath);
URLConnection connection=url.openConnection();
/**
* allowUserInteraction
如果爲 true,則在允許用戶交互(例如彈出一個驗證對話框)的上下文中對此 URL 進行檢查。
*/
connection.setAllowUserInteraction(true);

connection.setRequestProperty("Range", "bytes=" + start + "-"
+ end);
InputStream is= connection.getInputStream();
byte [] array=new byte[1024];
is.read(array);
File file=new File(filePath);
RandomAccessFile randomAccessFileile=new RandomAccessFile(file,"rw");
randomAccessFileile.seek(start);
int index=is.read(array);
while (index!=-1){
randomAccessFileile.write(array,0,index);
sum+=index;
index=is.read(array);
}
randomAccessFileile.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章