2016-09-26 73 views
1

在我的應用程序中,我通過HTTP連接從服務器下載媒體。無論如何連接斷開時(例如,沒有n/w,權限撤銷),下載文件時會部分下載。Android部分下載http

此前我們正在刪除文件並從頭開始下載。

現在,需求發生了變化。我必須從我離開的地方繼續(如在WhatsApp中)。

所以我正在做的是檢查文件的存在,如果文件存在跳過流。請找到下面的代碼片段。

InputStream is = con.getInputStream(); 

File file = new File(targetPath); 
boolean fileExist = file.exists(); 
if (fileExist) { 
    long skippedBytes = is.skip(file.length()); 
} 

// opens an output stream to save into file 
OutputStream os = new FileOutputStream(targetPath, fileExist); 

它的工作僅僅是跳過而實際上不工作。說,文件(視頻)的長度是20秒,並在第一次嘗試我下載了6秒,其後休息。但是當我播放它只是播放到6秒,然後拋出通常的視頻播放錯誤。

+1

使用'InputStream.skip'不作SENS ...它仍然會被下載,但跳過......如果服務器支持Range頭,我寧願用它 – Selvin

+0

@Selvin,我知道這不會救帶寬,但它應該工作。爲了節省帶寬,我們需要在服務器端跳過。我正試圖在客戶端實現(不用擔心帶寬)使用跳過。 –

+2

我寧願使用http頭'Range',如果它支持後端 – Blackbelt

回答

0
File file = new File(targetPath); 

if (file.exists()) { 
    con.setRequestProperty("Range", "bytes=" + (file.length()) + "-"); 
} else { 
    con.setRequestProperty("Range", "bytes=" + 0 + "-"); 
}