2010-11-16 51 views
2

我的應用程序需要下載一些大文件。我使用服務進行下載並顯示通知中的進度。問題是,在下載時間期間,用戶可以從3G切換到WIFI。在這種情況下,進度會停止,但不會引發異常。 如何正確處理這種情況?如何處理從3G到WIFI的切換? UrlConnection TimeOut不會拋出異常

URL url = new URL(myurl); 
URLConnection conexion = url.openConnection(); 
conexion.setReadTimeout(10000); 
conexion.setConnectTimeout(10000); 
conexion.connect(); 
int lenghtOfFile = conexion.getContentLength(); 
// downlod the file 
InputStream input = new BufferedInputStream(url.openStream()); 
OutputStream output = new FileOutputStream(targetFilePath); 

byte data[] = new byte[1024]; 

long total = 0; 
while ((count = input.read(data)) != -1) { 
    total += count; 
    // publishing the progress.... 
    updateProgress(downloadNM, downloadNotification, (int)total*100/lenghtOfFile); 
    output.write(data, 0, count); 
} 
output.flush(); 
output.close(); 
input.close(); 

回答

1

看看HttpClient-Library。它提供了比URL類更多的選項,並可能幫助你解決問題。

http://developer.android.com/reference/org/apache/http/client/HttpClient.html

+0

你介意解釋提問者的問題是如何用HttpClient實際解決的嗎?這比鏈接文檔更有用。 – LouieGeetoo 2011-08-17 22:51:15

+1

那麼,很可能HttpClient首先不會表現出相同的行爲。如果確實如此,他至少會有更好的工具來解決複雜的連接問題。 – 2011-08-18 14:57:12