Android 在使用静态 IP 时检查网络连接
在设备上使用静态 IP 时,我在检测互联网连接方面没有什么问题。当我在没有设置任何静态 IP 的情况下进行连接时,我用于检测可用连接的功能正常工作。但是当我设置静态 IP 时,该函数返回 true,因为我已连接到 Wifi 或 3G,但我没有任何互联网连接,因此我的应用程序在这种情况下崩溃了。有什么想法如何在使用静态 IP 时解决该问题吗? 这是我正在使用的:
public boolean chkNetworkStatus(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Toast.makeText(context, "No available connection!", Toast.LENGTH_LONG);
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
I have little issue with detecting internet connection while using static IP on device. While I'm connecting without setting any static ip my function for detecting available connection is working properly. But when I set static IP, the function return true, because I'm connected to Wifi or 3G, but I don't have any internet connection and so my app crashes in that situation. Any ideas how to fix that problem while using static ip?
Here is what I'm using :
public boolean chkNetworkStatus(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Toast.makeText(context, "No available connection!", Toast.LENGTH_LONG);
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用这个方法......我希望它对你有帮助。
公共布尔checkNetworkConnection(上下文上下文){
Use this method.... I hope it will helpfull for you.
public boolean checkNetworkConnection(Context context) {
以下是您可以根据自己的情况使用的内容。如果您连接到 wifi/3g 并且可以加载任何网页,此函数将返回
true
。Here is what you can use in your situation. This function will return
true
if you are connected to wifi/3g and you can load any web page.