ConnectivityManager 用于验证互联网连接
大家好,我需要验证我的设备当前是否连接到互联网,因此我编写了这个使用 ConnectivityManager
来检查的类:
public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
效果很好,因为现在该方法位于main 包(com.App
),但是我应该如何更改代码以使其在 com.App.Utility
中定义的类中工作?
谢谢!
Hi all I need to verify if my device is currently connected to internet or not and so I wrote this class that uses a ConnectivityManager
to check:
public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
works great, because right now the method is in a class in the main package (com.App
), but how should I change the code to make it work in a class defined in com.App.Utility
?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 getActiveNetworkInfo() 的唯一问题是,在许多情况下它无法正确检测连接。例如,如果手机上的移动网络被禁用,但 wifi 可用,则活动网络仍可能被算作移动网络,因此返回 false。
另一种选择是:
The only issue with using getActiveNetworkInfo() is that there are a number of situations where is will not correctly detect connectivity. For example if the mobile network is disabled on a phone but wifi is available then the active network may still be counted as the mobile network and therefore return false.
An alternative is:
谢谢艾伦 H!
当netInfoMob和netInfoWifi之一为空而另一个不为空时,if条件可能会导致NPE。
这对我有用:
Thx Alan H!
The if condition may cause NPE when one of netInfoMob and netInfoWifi is null but the other not.
This one works for me:
试试这个,这段代码有效。
Try this , this code works.
您可以使用
kotlin
轻松检查。You can easily check with
kotlin
.