我使用 wifi 和 GPRS 连接互联网。但在某些情况下,例如 wifi 连接但没有互联网连接,数据 (GPRS) 也是如此。有数据但没有网络连接。
对于 wifi,我使用下面的代码。这始终返回 true
public static boolean isConnectedWifi(Context context) {
NetworkInfo info=null;
if(context!=null){
info= IsNetConnectionAvailable.getNetworkInfo(context);
}
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
对于移动数据,我使用下面的代码。它会根据数据的开启或关闭给出 true 或 false。
public boolean isMobileDataEnable() {
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean) method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API and do whatever error handling you want here
}
return mobileDataEnabled;
}
但是当两种情况都没有互联网连接时如何捕获这种情况?有没有任何 android api 可以帮助解决上述情况。 请帮我解决这个问题。
最佳答案
获取网络类型是移动还是wifi的方法。
public static String getNetworkType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info.getTypeName();
}
检查手机是否连接INTERNET的方法
public static boolean isInternetIsConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
return true;
}
} else {
// not connected to the internet
return false;
}
return false;
}
您可以使用以下library对网络连接进行更多控制。
关于android - 如何以编程方式检查 wifi 是否已连接或数据包已启用但没有互联网连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48077755/