【问题标题】:Check if internet connection is available (https) [duplicate]检查互联网连接是否可用(https)[重复]
【发布时间】:2020-03-02 15:16:19
【问题描述】:

我想检查安卓应用程序是否有可用的互联网连接。 我试过这个可以,由于谷歌对 https 的要求,它不起作用。

private static boolean netIsAvailable() {
    try {
        final URL url = new URL("http://www.google.com");
        final URLConnection conn = url.openConnection();
        conn.connect();
        conn.getInputStream().close();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.d(TAG, e.toString());
        return false;
    }

我收到错误消息:java.io.IOException: Cleartext HTTP traffic to www.google.com not permitted

还有哪些方法?

【问题讨论】:

标签: java android


【解决方案1】:

使用https://developer.android.com/reference/android/net/ConnectivityManager 是一个选项:

类似:

 NetworkCapabilities networkCapabilities = mConnectivityService.getNetworkCapabilities(mConnectivityService.getActiveNetwork());
                if (networkCapabilities != null) {
                    if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {

                        // do something with internet
                    } else {
                        // no internet
                    }
                } else {
                    // no internet
                }

尽管如此,你有什么理由不能在你的 URL 中只使用 https 吗?

【讨论】:

  • 只使用https会导致android.os.NetworkOnMainThreadException
  • mConnectivityService 是什么?
  • 那是因为你试图在主线程上做请求,做为AsyncTask或类似的
  • mConnectivityServiceConnectivityManagermConnectivityService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  • 这似乎工作:private boolean netIsAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = 连接管理器.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 2017-06-07
  • 2019-10-27
  • 2017-11-30
  • 2012-03-23
相关资源
最近更新 更多