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

问题描述 投票:0回答:2

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

android android-wifi gprs
2个回答
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
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.