I\'m writing an application that connects to a webservice and I don\'t want it to wait too long if it can\'t get a connection. I therefore set the connectionTimeout of the h
With the marked solution I am still getting a UnknownHostException after 30+ seconds. In this case the device is connected to a wifi router but there is no internet access.
The approach taken was to kick off an AsyncTask that will just attempt to resolve the hostname. The blocking call checks every 250 ms to see if it succeeded, and after 4 seconds it will cancel the task and return.
This is what I did to solve it:
private boolean dnsOkay = false;
private static final int DNS_SLEEP_WAIT = 250;
private synchronized boolean resolveDns(){
RemoteDnsCheck check = new RemoteDnsCheck();
check.execute();
try {
int timeSlept = 0;
while(!dnsOkay && timeSlept<4000){
//Log.d("RemoteDnsCheck", "sleeping");
Thread.sleep(DNS_SLEEP_WAIT);
timeSlept+=DNS_SLEEP_WAIT;
//Log.d("RemoteDnsCheck", "slept");
}
} catch (InterruptedException e) {
}
if(!dnsOkay){
Log.d("resolveDns", "cancelling");
check.cancel(true);
Log.d("resolveDns", "cancelled");
}
return dnsOkay;
}
private class RemoteDnsCheck extends AsyncTask{
@Override
protected Void doInBackground(Void... params) {
try {
Log.d("RemoteDnsCheck", "starting");
dnsOkay = false;
InetAddress addr = InetAddress.getByName(baseServiceURL);
if(addr!=null){
Log.d("RemoteDnsCheck", "got addr");
dnsOkay = true;
}
} catch (UnknownHostException e) {
Log.d("RemoteDnsCheck", "UnknownHostException");
}
return null;
}
}
Then, any time I want to do a web call, this is called at the beginning of the function:
if(!resolveDns()){
return null;
}