Question

I have an interesting issue.

I have an application where inside of it, I'm trying to account for the condition where the phone is connected to a router, but that router is not connected to the internet.

I've tried multiple methods of establishing the connection, but NONE of the timeouts account for this condition.

I've tried:

HttpParams httpParameters = new BasicHttpParams();
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutSocket);

I've also tried:

HttpURLConnection huc = (HttpURLConnection)serverAddress.openConnection();

huc.setDoOutput(true);
huc.setRequestMethod("PUT"); // For amazon
//huc.setRequestMethod("POST"); // For regular server.
huc.setRequestProperty("Content-Type", "text/plain");
huc.setRequestProperty("Content-Length", String.valueOf(bytes));
huc.setFixedLengthStreamingMode(bytes);
huc.setConnectTimeout(1000); // Establishing connection timeout
huc.setReadTimeout(1000);

But in BOTH cases, when I execute/ get the output stream, it takes about 20 seconds to receive an UnknownHostException error.

I would like that reduced to a maximum of 5 seconds before reaching that conclusion.

Is there any way to do this?

Cheers

Was it helpful?

Solution

Through lots of searching and through the help of this link I've found a solid solution that seams to be working so far.

My understanding of the conclusion is that when I use methods like:

DataOutputStream wr = new DataOutputStream(huc.getOutputStream());

or

InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

(uploading or downloading)

There is a lot of things happening under the hood. Including a DNS lookup call. With no-connectivity, but while connected to a router, this is taking about 20 seconds to finally reach a UnknownHostException.

However, if I add this line of code first before the above code is executed:

InetAddress iAddr = InetAddress.getByName("myserverName.com");

Then it will give me the proper SocketTimeOutException and responds exactly how I would hope/expect it to. The above line of code apparently caches the DNS Lookup, and the timeouts work as expected.

Also, something to note: that once the failure is cached, executing the code above will take as long to fail as the other previous code. (Can't tell you exactly what will trigger this) But if you connect to the internet again, and then enter the connected but no connectivity state again, the earlier success will be cached and the timeouts will again work properly.

This wasn't particularly easy to find or figure out, so I hope this helps somebody.

Cheers,

OTHER TIPS

You could implement a CountDownTimer that has a limit of 5000ms see this http://dewful.com/?p=3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top