0

Is there a way to set a Timeout to an InputStream?

My current code looks like that:

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");
Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57
Styler2go
  • 604
  • 2
  • 12
  • 32

2 Answers2

3

I think For you requirement you can use

HttpURLConnection.setReadTimeout()

Mab be these links will helps you.

  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?
Community
  • 1
  • 1
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
  • 1. Also in addition use connectionTimeout() for closing sockets if connection do not happen within desired time 2.Want to handle the 'slow server' case? i.e. a server that sends small chunk of data after every 'x' seconds. Such a server would reset the readTimeout every time thus the whole 'read' operation would take pretty long. To handle this scenario, use two threads, first thread that would handle your 'read' operation. Second thread would sleep for 'y' seconds. When it wakes up and if first thread is still running, it kills the first thread. – Rusheel Jain Mar 16 '16 at 22:37
0

You could start an AsyncTask or just a separate thread and sleep it for the timeout time and then check if the transaction is ready. Or even better, you could postDelayed a message to a Handler, and then check if your task is ready. You could use a timer too, but I think the Handler solution is the most elegant.

Take a look at this: http://developer.android.com/reference/android/os/Handler.html

Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53