2012-10-16 18 views
0

有沒有辦法將InputStream設置爲超時?InputStream超時

我當前的代碼看起來像這樣:

public class DownloadFile implements Runnable { 
private EventHandler eh; 
private String source; 
private String destination; 

public void run(){ 
    try { 
     Log.d("Download", "Download... " + source); 
     URL url = new URL(source); 

     URLConnection connection = url.openConnection(); 
     connection.connect(); 

     int fileLength = connection.getContentLength(); 

     InputStream input = new BufferedInputStream(url.openStream()); 
     OutputStream output = new FileOutputStream(destination + "t"); 

回答

3

我想對你的要求,你可以使用

HttpURLConnection.setReadTimeout() 

單抗這些鏈接將幫助你。

  1. Is it possible to read from a Java InputStream with a timeout?
  2. Class HttpURLConnection
  3. Can I set a timeout for a InputStream's read() function?
+0

1.另外,如果在所需時間內沒有發生連接,還要使用connectionTimeout()來關閉套接字。 2.想處理「慢服務器」情況?即在每'x'秒後發送小塊數據的服務器。這樣的服務器會每次重置readTimeout,因此整個「讀取」操作將花費相當長的時間。爲了處理這種情況,使用兩個線程,第一個線程將處理您的「讀取」操作。第二個線程會睡眠'y'秒。當它醒來時,如果第一個線程仍在運行,它會殺死第一個線程。 –

0

則可能會啓動的AsyncTask或只是一個單獨的線程和睡眠它的超時時間,然後檢查,如果該交易已準備就緒。或者甚至更好,你可以發佈消息給Handler,然後檢查你的任務是否準備就緒。您也可以使用計時器,但我認爲Handler解決方案是最優雅的。

看看這個:http://developer.android.com/reference/android/os/Handler.html

+0

我的問題是,它interrputs同時下載和永遠不會結束。 – Styler2go

相關問題