问题
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".
回答1:
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.
回答2:
UnKnownHostException is thrown to indicate that the IP address of a host could not be determined. It is not the case that no internet connection or server is down.
also check whether you had added internet permission in manifeast file.
Please refer this LINK
To check internet connection use bwlow method::
//To check whether network connection is available on device or not
public boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
And if server is down mostly you will get Connection timeout Exception
回答3:
You can use the ConnectivityManager to check for network status.
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
bool hasConnectivity = connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
来源:https://stackoverflow.com/questions/9993232/how-to-know-the-cause-of-unknownhostexception