如何以编程方式检查已连接wifi或启用数据包但没有互联网连接?

时间:2018-01-03 12:48:32

标签: android android-wifi gprs

我使用wifi和GPRS连接互联网。但在某些情况下,如wifi连接但没有互联网连接,与数据(GPRS)相同。数据但无网络连接。

对于wifi我正在使用下面的代码。这总是返回

 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可以帮助上述情况。 请帮我解决这个问题。

2 个答案:

答案 0 :(得分:4)

获取网络类型的方法,无论是移动还是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来更好地控制网络连接。

答案 1 :(得分:1)

您可以使用此Facebook Connection Class查找网络速度以及您是否已连接到网络。对于每个活动,您不需要检查只创建一个Application Class并实现逻辑,并通过该类获取连接检查器。

我已经为Live Streaming实现了这个功能,无论我是否具有指定范围的带宽的活动网络连接。我的方案没有可用的代码。这可能有所帮助。

相关问题