使用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;
}