【问题标题】:Check the stable Internet检查稳定的互联网
【发布时间】:2021-05-21 09:07:51
【问题描述】:

我的应用程序使用 getInet4AddressByName () 方法。它需要打开互联网。为了检查 Wi-Fi 状态,我使用了 BroadcastReceiver 接收器。但是开启 Wi-Fi 一段时间后网络稳定,方法来不及正常工作getInet4AddressByName()返回错误。如何跟踪稳定的 Internet 连接而不是 wi-fi 连接的存在?谢谢。

@Override
public void onReceive(Context context, Intent intent) {
 WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 if (wifi.isWifiEnabled()) {
   tv.setText("You are connected");
 } else {
   tv.setText("You are NOT connected");
 }
}
};

【问题讨论】:

  • 认为你想要的是ConnectivityManager

标签: java android android-wifi wifimanager


【解决方案1】:

你可以使用两种方法:

Google 推荐使用此代码块检查互联网连接。因为即使连接到 WiFi,设备也可能没有互联网连接。 1 - 检查连接:

 private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null;
}

2 - 检查互联网:

  public boolean internetIsConnected() {
    try {
        String command = "ping -c 1 google.com";
        return (Runtime.getRuntime().exec(command).waitFor() == 0);
    } catch (Exception e) {
        return false;
    }
}

向清单添加权限:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

【讨论】:

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