I am working on an Android app that needs to read a line from a web page right when it starts. I am doing this with the following code:
try{
URL url
Probably better solution if you setConnectionTimeout to 5 sec, catch SocketTimeoutException and show Toast from there. When you set ConnectionTimeout to some value and connection didn't get response code will throw SocketTimeoutException. Here you can catch it and call handler to show a toast in UI. Finally will close the connection and release memory.
class MyHttpClient extends DefaultHttpClient {
@Override
protected ClientConnectionManager createClientConnectionManager() {
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https",
mSSLSocketFactory != null
? mSSLSocketFactory
: SSLSocketFactory.getSocketFactory(),
443));
return new SingleClientConnManager(getParams(), registry);
}
MyHttpClient httpClient = new MyHttpClient();
// set http params
HttpParams params = httpClient.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(30000));
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(30000));
httpClient.setParams(params);
....
httpClient.execute(httpUriRequest)
Consider using AndroidHttpClient
class instead, it has nice preset timeouts so you wouldn't have to do anything.