我正在使用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;
}
但是,当两种情况下都没有互联网连接时,如何捕获条件? 是否有任何安卓API可以帮助上述情况。请帮助我解决这个问题。
网络类型的方法是移动或wifi。
public static String getNetworkType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info.getTypeName();
}
检查手机是否连接到互联网的方法
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;
}
您可以使用以下库对网络连接进行更多控制。
您可以使用此 Facebook 连接类来查找网络速度以及您是否连接到网络。对于每个活动,您不需要检查仅创建一个应用程序类并实现逻辑,并通过该类获取连接检查器。
我已经为实时流式传输实现了这一点,无论我是否具有具有指定带宽范围的活动网络连接。我没有适用于您的方案的工作代码。它可能会有所帮助。