Search code examples
javaandroidexceptionunknown-host

How to know the cause of UnknownHostException?


An UnknownHostException is thrown if a server is down or if there is no internet connection. How can I determine if the UnknownHostException is thrown because the server is down or there is no internet connection?

The reason for this is I need to notify the user about the cause of the error. And I have to display something like this "Sorry. The service is currently not available. Please try again later" or "You do not have an internet connection".


Solution

  • You could check the network state to determine if an internet connection is available (not 100% reliable though):

    ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    
    if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED 
        ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {
    ...
    }
    

    EDIT :

    IMHO, there is no way to tell for sure that the phone internet connectivity is down. But you could, in addition to checking the network state, make a simple test like downloading a small page from a website on the internet (pick some reliable server).

    The result of this double test should be accurate 99% of the time.