当我使用下面的代码显示我的连接状态时,“if”条件总是返回“true”,除非我把“netinfo”等于“null”。
问题出在哪里?
public boolean isConnectedToInternet()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if ( netInfo.isConnectedOrConnecting())
{
Toast.makeText(this, "On",Toast.LENGTH_LONG).show();
Log.i("NewsList", "Internet Connection found.");
return true;
}
Toast.makeText(this, "Off",Toast.LENGTH_LONG).show();
return false;
}
答案 0 :(得分:1)
请尝试以下操作:
<强> DetectConnection.class:强>
public class DetectConnection {
/*
* Checking internet connection
*/
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
}
从其他活动检查互联网:
if (DetectConnection.checkInternetConnection(this)) {
//do something
}