如何知道UnknownHostException的原因? [英] How to know the cause of UnknownHostException?

查看:1390
本文介绍了如何知道UnknownHostException的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果服务器关闭或没有互联网连接,则会抛出 UnknownHostException 。如何确定是否由于服务器关闭或没有互联网连接而抛出 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".

推荐答案

您可以检查网络状态以确定是否可以使用Internet连接(尽管并非100%可靠):

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 :

恕我直言,无法告诉确定电话互联网连接已断开。
但是,除了检查网络状态之外,您还可以进行简单的测试,例如从Internet上的网站下载一个小页面(选择一些可靠的服务器)。

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).

此双重测试的结果应该在99%的时间内都是准确的。

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

这篇关于如何知道UnknownHostException的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆