我似乎面临网络检查不可靠的问题。我的意思是,当实际网络不可用时,它有时会返回true。
这种情况发生在现实世界的场景中,当你进入地下并且信号松动时,手机正确报告它没有显示任何条形但检查仍然会返回true。
我正在使用以下代码:
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean isNetworkAvailalbe = (activeNetworkInfo != null);
我正在寻找实施可靠网络检查的最防弹方式,任何建议?
答案 0 :(得分:1)
试试这个..
public static boolean checkNetworkRechability(Context mContext) {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
isInternetAvailable();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static boolean isInternetAvailable() {
Log.i("TAG", "isInternetAvailable start");
try {
InetAddress ipAddr = InetAddress.getByName(new URL("google.com").getHost());
String ip = ipAddr.getHostAddress();
if (ip.equals("")) {
return false;
} else {
Log.i("TAG", "IP Address : " + ip);
return true;
}
} catch (Exception e) {
return false;
}
}
答案 1 :(得分:1)
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
在Android Developer门户网站上,您可以找到更多信息:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html