2012-01-29 111 views
0

我正在使用下面的代碼下載視頻,並維護一個進度條來顯示下載已完成的程度。在Android上下載文件大於文件大小

ByteArrayBuffer baf = new ByteArrayBuffer((int)filesize); 
long current = 0; 
long notificationSize = filesize/100 * 5; 
int notifyCount = 0; 
while ((current = inStream.read()) != -1) 
{ 
    baf.append((byte) current); 
    count += current; 

    //only process update once for each kb 
    if(count > notificationSize * notifyCount) 
    { 
     notifier.processUpdate(count); 
     notifyCount++;; 
    } 

} 

我遇到的問題是從輸入流返回的數據加起來多於文件大小。意味着我的進度條在下載完成之前完成。

例如,我正在下載一個文件大小爲1,849,655字節的視頻,但下載次數增加到228,932,955。

Android進度條使用完成過程的百分比。如果下載的總字節數超過文件的大小,我怎麼知道完成了多少?

+0

你如何分配文件大小的值? – 2012-01-29 23:47:52

+0

我正在通過兩種方法來確保我的尺寸合適。大小是在RSS源中,我從中獲取文件位置。我也使用URLConnection實例中的getContentLength。兩者都會返回與下載文件大小相同的文件大小 – Stimsoni 2012-01-29 23:50:41

+0

找到解決方案。這是因爲read()每次只讀取一個字節,但返回的讀取字節數多於一個。我稍後會發布完整的解決方案,因爲我沒有權限快速回答我自己的問題。 – Stimsoni 2012-01-30 01:15:20

回答

0

解決了這個問題。

下載並跟蹤下載的數據量時,請勿使用BufferedInputStream中的read()。

改用read(buffer,offset,length);

我還更改了我的代碼,將數據寫出到文件中,而不是將數據存儲在內存中,並在所有數據都刪除後輸出。

byte[] baf = new byte[filesize]; 
int actual = 0; 
int count = 0; 
long notificationSize = filesize/100 * 5; 
int notifyCount = 0; 
while (actual != -1) 
{ 
    //write data to file 
    fos.write(baf, 0, actual); 
    count += actual; 

    //only process update once for each kb 
    if(count > notificationSize * notifyCount) 
    { 
     notifier.processUpdate(count); 
     notifyCount++;; 
    } 
    actual = inStream.read(baf, 0, filesize); 
} 

我真的不知道爲什麼閱讀()顯示它在讀取時已經讀出多個字節()僅僅意味着在一次讀取一個字節。

如果你真的想使用read()變化

count += current; 

count++; 

這雖則下載作爲while循環的循環數量相當低效的方式要大得多。在進行一些簡短的性能測試後,下載速度似乎也會變慢(因爲它需要爲每個字節寫入文件而不是一大塊字節)。