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

标签 android android-wifi gprs

我使用 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/

相关文章:

android - 添加Material Spinner依赖项时出现Gradle同步错误

android - Phonegap 运行 android 报错

android - Google home 如何以编程方式获取特定 wifi 的密码?

android - Facebook 应用程序类型无互联网连接消息

java - 不幸的是,<project name> 已停止

安卓通讯: Phone to Phone Application Control over 3G

java - 以编程方式打开请勿打扰,但有异常(exception)

javascript - 如何使用javascript更改android webView的字体

c# - 通过 gprs 从设备读取消息

带 GPS 和 GPRS 的 Android 15 天