我使用以下代码来检查互联网连接。
public static boolean checkNetworkConnection(Context context) {
boolean connected = true;
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState() == android.net.NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == android.net.NetworkInfo.State.CONNECTED) {
connected = true;
} else
connected = false;
}
此代码在以下移动设备中运行良好。但它不适用于 Google nexus 7 (android 4.2)。
当我在 Google nexus 7 (android 4.2) 中测试此代码时。我有错误。
连接管理器中的空指针异常
最佳答案
对我来说它有效:
public static boolean isInternetEnabled() {
ConnectivityManager conMgr = (ConnectivityManager) YourApp.context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
return true;
else
return false;
}
关于android - 如何在 Google nexus 7 (android 4.2) 中检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230965/