本文介绍了使用Context.CONNECTIVITY_SERVICE检查互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用这code来检查网络连接:
I am using this code to check for the internet connection:
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
但即使当我关闭了WiFi它仍然返回true。
but even when I turn off the wifi it still returns true.
在仿真器和设备具有相同的结果都尝试?
什么是错的?
Tried both on emulator and device with same result?
What is wrong ?
推荐答案
这个简单的code工作在我的情况:
This simple code works in my case:
public boolean netConnect(Context ctx)
{
ConnectivityManager cm;
NetworkInfo info = null;
try
{
cm = (ConnectivityManager)
ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
}
catch (Exception e)
{
e.printStackTrace();
}
if (info != null)
{
return true;
}
else
{
return false;
}
}
另外这一个。
Also this one..
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
这篇关于使用Context.CONNECTIVITY_SERVICE检查互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!