JuiCe
JuiCe

Reputation: 4191

Is there an Android InputStream class that times out?

I am currently using an InputStream in my application (import java.io.InputStream) and have run into an issue regarding timing out. The way the InputStream seems to work is that it waits for a certain amount of bits and then proceeds. For my application this works a lot of the time, but there are cases where I am expecting the read to fail due to timeout. Does anyone know a way to do this?

I have found many examples of creating threads to run alongside the read() function and cancel it, but I was wondering if there is an existing class which lets me use an InputStream that times out.

Upvotes: 1

Views: 292

Answers (2)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

This largely depends on where you are reading from. If it is from a file (or local) socket, there is no timeout. If it is from a remote socket, you can specify timeout when creating the socket. If it times out you should get an exception. Using threads/AsyncTask is the way to go, but you generally cannot interrupt a blocked read, unless you are using Java NIO.

And no, it is not ridiculous, how do you propose for it to 'time out on its own'? Someone has to signal the timeout, and that someone is either some sort of monitor thread or the OS raising an error.

Upvotes: 1

Mike Marshall
Mike Marshall

Reputation: 7850

I would use AsyncTask<> for this. You can try to start reading the stream asynchronously and then at a time of your choosing cancel the task, rather than blocking your UI. Documentation here

Upvotes: 1

Related Questions