【发布时间】:2018-01-03 12:48:31
【问题描述】:
我正在使用 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);
}
对于移动数据,我使用以下代码。它会根据数据给出真假。
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可以帮助解决上述情况。 请帮我解决这个问题。
【问题讨论】:
-
对于一个网站,我会做一个简单的 XHR 请求来确定我是否可以连接到网络,也许你也可以这样做?
-
@mic 是的,我这样做了,但这很耗时。因为我应该在每个活动中检查网络连接
标签: android android-wifi gprs