【问题标题】:I want to check the Internet connection我想检查互联网连接
【发布时间】:2016-06-05 13:11:33
【问题描述】:

我试试代码

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

它只检查 WiFi 或移动网络的打开和关闭。但我想检查互联网访问。比如开启WiFi,但可以连接互联网。

【问题讨论】:

标签: android android-internet


【解决方案1】:

我在 Google 中使用 ping 检查用户是否有真正的互联网连接,如果您的用户在中国或任何其他被 Google 屏蔽的国家/地区,请小心。

public boolean isOnline() {

    Runtime runtime = Runtime.getRuntime();
    try {

        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e)          { e.printStackTrace(); } 
      catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2017-03-16
    • 2014-02-08
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多