我正在尝试检查互联网状态。当我启用互联网,然后我运行这个应用程序,它显示"互联网连接"。当我停止互联网然后再次运行此应用程序时,它将显示"未连接到互联网"。但是,当我在模拟器中运行此应用程序时,它始终显示Internet连接。请告诉我问题是什么。
//check Internet connection.
private boolean checkInternetConnection() {
ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null) {
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show();
}
return true;
} else {
Toast.makeText(context, "not connected to internet", Toast.LENGTH_SHORT).show();
return false;
}
}
答案 0 :(得分:0)
我猜问题就在于
NetworkInfo[] info = check.getAllNetworkInfo();
您只能获得有效的网络信息 您可以尝试以下方法,我测试它就像一个魅力:
public boolean isNetworkUp() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}
答案 1 :(得分:0)
你可以尝试这种方法.......
private boolean isNetConnected(){
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnectedOrConnecting()){
return true;
}
return false;
}
答案 2 :(得分:0)
您好使用以下代码..
/**
* Checks if is connection.
*
* @param con
* the con
* @return true, if is connection
*/
public static boolean isConnection(Context con) {
ConnectivityManager conMgr = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
让我知道您的反馈意见。
答案 3 :(得分:0)
You can also use F8 to set the cell network on/off.
Check this link
http://developer.android.com/tools/help/emulator.html
答案 4 :(得分:0)
这将是您的问题的解决方案。
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()){
return true;
}else {
return false;
}
}