检查 Android 互联网连接的完美功能,包括蓝牙锅

The perfect function to check Android internet connectivity including bluetooth pan

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

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

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

我尝试了 运行 其他几个应用程序。它们也显示没有网络连接,但是 google 应用程序运行完美,就像 whatsap 等其他一些应用程序一样。想知道他们是怎么做到的,以及为什么大多数应用程序都忽略了这一点..

任何人都可以告诉我一种方法来检查 android 中的互联网连接,通过所有可用的方式,包括蓝牙 pan 和代理等

如有任何帮助,我们将不胜感激。提前致谢..

检测 phone(或任何其他设备)是否连接到互联网的最简单方法是向我眼中的网络服务器发送 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 状态、蓝牙状态或其他更改时,您都必须 运行 此方法(我建议在单独的线程中),但总而言之,它应该可以解决您的问题。

尝试连接到 "always available" 网站。如果存在任何连接,这应该 return 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;
}

这可能有用,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;
            }

您可以使用以下内容:

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

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

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" />

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

我就是这样解决的。

已创建 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;
}

}

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

    // 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;
    }

通过移动数据、蓝牙、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;
}