多線程斷點下載sql
首先,在下載文件的時候大部分是在後臺進行下載的,因此須要用到服務數據庫
下載文件須要四步:網絡
第一步:獲取文件的大小和在本地騰出相應的下載空間多線程
1,由於鏈接網絡是耗時的操做,因此要放在線程裏用HttpURLConnection鏈接網絡dom
第二步:用RandomAccessFile 的setLength()在本地爲下載的文件騰出空間優化
第三步:爲每條下載線程分配下載的區域範圍(通常都會在最後的線上分多一點的任務)url
1,把新添加的下載文件的下載線程信息添加到數據庫中spa
2,用線程池啓動線程線程
3,判斷每一個文件下載是否完成,若是下載完成就發送廣播通知code
第四步 執行下載操做(下載操做就是對每條下載線程的下載資源的操做)
下載先須要對內存卡的狀態進行判斷
URL url=new URL(threadclass.getUrl());
http=(HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setReadTimeout(5000);
int start=threadclass.getStart()+threadclass.getFinished(); //若是以前下載過就把該線程的開始位置和下載的資源相加
http.setRequestProperty("Range", "bytes="+start+"-"+threadclass.getEnd());
File file=new File(MyService.DOWN_FILE,soft.getName()); //下載文件的路徑
access=new RandomAccessFile(file, "rwd"); //爲暫停後的下載做標籤
access.seek(start);
mfinished=mfinished+threadclass.getFinished(); //以前若下載過,把以前的起源加起來
Intent intent2=new Intent(MyService.UPDATA_ACTION); //用於下載進度更新數據發送
int code=http.getResponseCode();
if(code==206){
in=http.getInputStream();
int len=-1;
byte[] arr=new byte[1024*4];
long time=System.currentTimeMillis(); //當前的系統時間
while((len=in.read(arr))!=-1){
access.write(arr, 0, len);
threadclass.setFinished(threadclass.getFinished()+len); //每條下載線程進度的更新
mfinished=mfinished+len; //總的進度下載
//每隔1秒發送進度
if(System.currentTimeMillis()-time>1000){
time=System.currentTimeMillis();
intent2.putExtra("finished", mfinished*100/soft.getLength()); //進度更新
intent2.putExtra("id", soft.getId()); //判斷那個文件下載
conn.sendBroadcast(intent2); //發送廣播
}
//若是標籤爲true直接把下載循環暫停
if(isDown){
sqlservice.updataThreadClass(threadclass.getFinished(), threadclass.getId(), threadclass.getUrl());
return;
}
}
//若是該線程下載完畢那麼該標籤就變成true
isFinished=true;
//監聽每條線程下載資源是否完成
checkAllThreadFinished();
注意:在下載的時候,線程累加的問題,也是項目優化的一部分,就是在用完線程或
輸入流,輸出流時對其一一關閉,對資源的不浪費也會起到很大的做用