【问题标题】:The perfect function to check Android internet connectivity including bluetooth pan检查 Android 互联网连接的完美功能,包括蓝牙盘
【发布时间】:2018-03-26 15:33:06
【问题描述】:

我的应用程序在 wifi 和移动网络中运行良好,但无法检测到何时通过蓝牙网络共享连接。

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

我尝试运行其他一些应用程序。他们也显示没有网络连接,但谷歌应用程序运行完美,其他一些应用程序(如 whatsap)也是如此。想知道他们是如何做到的,以及为什么大多数应用程序都忽略了这一点..

谁能告诉我一种通过所有可用方式(包括蓝牙泛和代理等)检查 android 中互联网连接的方法。

任何帮助将不胜感激。提前谢谢..

【问题讨论】:

  • 是检测蓝牙的tethering状态,不是通过它检查网络连通性
  • 只要尝试 ping 诸如 google 之类的网站,无论连接来自何处。
  • 这些答案都错过了:您应该使用 ConnectivityManager.requestNetwork(),这样它就可以打开 Wifi/蓝牙/无论您需要什么。例如,如果 Android 禁用了数据,简单地检查连接对您没有帮助。

标签: android android-bluetooth


【解决方案1】:

尝试连接到“始终可用”的网站。如果存在任何连接,则应返回 true:

protected static boolean hasInternetAccess()
{
    try
    {
        URL url = new URL("http://www.google.com");

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:1");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30);
        urlc.connect();

        // http://www.w3.org/Protocols/HTTP/HTRESP.html
        if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
        {
            // Requested site is available
            return true;
        }
    }
    catch (Exception ex)
    {
        // Error while trying to connect
        return false;
    }
    return false;
}

【讨论】:

  • 好主意,也是最简单的。这很实用。但我试图找到互联网连接并确定连接模式,即使它可能没有必要,总是。
  • 是否值得消耗数据和等待 ping 返回的时间?只检查手机连接状态不是更容易吗?
  • @FernandoCarvalhosa 这取决于您的情况。在我看来,在大多数情况下等待响应返回不是问题(通常,当没有连接时,它会在几毫秒甚至更短的时间内返回)。检查连接状态并不能回答“我有 Internet 连接吗?”这个问题。当您连接到无法访问 Internet 的 wifi 连接或通过蓝牙连接时
  • 这是一个糟糕的实现
【解决方案2】:

这可能有帮助,getAllNetworkInfo() 提供网络信息列表

 public boolean checkNetworkStatus(Context context) 
            {
                boolean flag = false;
                ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo[] netInfo = cm.getAllNetworkInfo();

               //it provide all type of connectivity ifo
                for (NetworkInfo ni : netInfo)
                {
                    if (ni.getTypeName().equalsIgnoreCase("Connecxtion Type"))
                        if (ni.isConnected())
                            flag = true;
                }
                return flag;
            }

【讨论】:

  • 之前尝试过,但无法识别蓝牙泛网络。
【解决方案3】:

检测手机(或任何其他设备)是否连接到互联网的最简单方法是向我眼中的网络服务器发送 ping。当然,您需要一个始终可以访问的 IP 地址。你可以试试这段代码(我的脑子里),也许你必须捕获一些异常:

public boolean hasInternetConection() {
    Runtime runtime = Runtime.getRuntime();
    Process ping = runtime.exec("/system/bin/ping -c 1 173.194.39.4"); // google.com

    int result = ping.waitFor();

    if(result == 0) return true;
    else return false;
}

当然,每次 wifi 状态、蓝牙状态或其他东西发生变化时,您都必须运行此方法(我建议在单独的线程中),但总而言之,它应该可以解决您的问题。

【讨论】:

  • 我认为很好,最小的方式。我在 adb shell 中尝试了该命令,但它失败了。将尝试使用代码。希望它适用于所有设备,无需生根。
  • 它应该可以在所有没有root的手机上运行。让我知道它是否对你有帮助:)
  • 是否值得消耗数据和等待 ping 返回的时间?只检查手机连接状态不是更容易吗?
【解决方案4】:

您可以使用以下内容:

public boolean isMyNetworkIsLive() {
    boolean isConnectionActive = false;
    ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    if (nNetworkInfo != null && nNetworkInfo.isConnectedOrConnecting()) {
        isConnectionActive = true;
    }
    return isConnectionActive;
}

来自Test Internet Connection Android的参考

【讨论】:

    【解决方案5】:

    您的互联网连接检查似乎没有问题。关于蓝牙连接,试试这个:

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
        // Bluetooth enabled
    }  
    

    你的完美功能应该是这样的:

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    
        return networkInfo != null && networkInfo.isConnected()
               bluetoothAdapter != null && bluetoothAdapter.isEnabled() 
    }
    

    我认为您将需要这些权限:

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

    【讨论】:

    • 对于蓝牙连接 - 这仅检查蓝牙是否启用,但不检查蓝牙网络共享是否处于活动状态。在所有情况下(蓝牙、wifi、蜂窝网络),这都不能回答“我有互联网连接吗?”这个问题。因为您可能连接到没有 Internet 连接的 wifi 网络(封闭/专用网络、需要登录的网络等...)
    【解决方案6】:

    我同意 Muzikant 的观点,并感谢您的想法。我认为发布实施的解决方案会更好,因为它需要一些补充。

    我就是这样解决的。

    Created 和 AsyncTask 以避免网络主线程异常。

    public class GetInternetStatus extends AsyncTask<Void,Void,Boolean> {
    
    @Override
    protected Boolean doInBackground(Void... params) {
    
        return hasInternetAccess();
    }
    
    protected  boolean hasInternetAccess()
    {
    
        try
        {
            URL url = new URL("http://www.google.com");
    
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application:1");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000 * 30);
            urlc.connect();
    
            // http://www.w3.org/Protocols/HTTP/HTRESP.html
            if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
            {
                // Requested site is available
                return true;
            }
        }
        catch (Exception ex)
        {
            // Error while trying to connect
            ex.printStackTrace();
            return false;
        }
        return false;
    }
    

    }

    现在将以下函数添加到活动并调用它来检查连接。

        // Checking for all possible internet connections
        public static boolean isConnectingToInternet() {
            Boolean result = false;
            try {
                //get the result after executing AsyncTask
                result = new GetInternetStatus().execute().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return result;
        }
    

    【讨论】:

      【解决方案7】:

      通过 - 移动数据、蓝牙、Wifi 检查互联网连接

        /**
       * To check internet connection
       *
       * @param context context for activity
       * @return boolean true if internet is connected else false
       */
      public static boolean isInternetConnected(Context context) {
          ConnectivityManager connec = (ConnectivityManager) context
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
          android.net.NetworkInfo wifi = connec
                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
          android.net.NetworkInfo mobile = connec
                  .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
          android.net.NetworkInfo bluetooth = connec
                  .getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);
      
          if (wifi.isConnected()) {
              return true;
          } else if (mobile.isConnected()) {
              return true;
          } else if(bluetooth.isConnected()){
              return true;
          } else if (!mobile.isConnected()) {
              return false;
          }
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 2016-08-28
        • 2012-02-21
        • 2016-01-16
        • 2017-11-30
        • 2013-02-02
        • 2011-02-14
        相关资源
        最近更新 更多