如何检查 android 设备是否已连接到互联网?

How I can check android device is connected to the Internet?

有什么方法可以查明 android 设备是否已连接到互联网。我使用这个功能:

    public boolean isDeviceOnline() {     
        ConnectivityManager cm =
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();     
        return netInfo != null && netInfo.isConnectedOrConnecting(); 
    }

但是如果设备连接到不包括互联网访问或需要基于浏览器的身份验证的 WiFi 网络,则此功能 return 为真,在这种情况下我希望 return 为假。

试试这个

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context) {
    this._context = context;
}

public boolean isInternetAvailble() {
    return isConnectingToInternet() || isConnectingToWifi();
}

private boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}

private boolean isConnectingToWifi() {
    ConnectivityManager connManager = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (mWifi != null) {
        if (mWifi.getState() == NetworkInfo.State.CONNECTED)
            return true;
    }
    return false;
} }

这样声明

ConnectionDetector ConnectionDetector = new ConnectionDetector(
            context.getApplicationContext());

一样使用
ConnectionDetector.isInternetAvailble()

试试这个方法>

public boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null; // return true =(connected),false=(not connected)
}

改变这个:

return netInfo != null && netInfo.isConnectedOrConnecting();

收件人:

return netInfo != null && netInfo.isConnected();

那就这样称呼吧

if(!isDeviceOnline()) {
    System.out.println("Not connected");
}