检查Android上是否可以访问Internet

时间:2012-07-26 05:10:19

标签: android

我如何检查互联网是否有。但我发现这个代码但是当wifi连接时它返回true,但我知道没有互联网。没有互联网接入。

 public boolean chechInternet_con(){
    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);

    // Here if condition check for wifi and mobile network is available or not.
    // If anyone of them is available or connected then it will return true, otherwise false;

    if (wifi.isConnected() || mobile.isConnected()) {
        return true;
    } 
    return false;

}

3 个答案:

答案 0 :(得分:1)

试试这个,

public boolean isInternetOn(Context ctx) {
        this.mContext = ctx;
        ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        State connected = NetworkInfo.State.CONNECTED;
        State connecting = NetworkInfo.State.CONNECTING;
        State disconnected = NetworkInfo.State.DISCONNECTED;

        State info0 = Connect_Manager.getNetworkInfo(0).getState();
        State info1 = Connect_Manager.getNetworkInfo(1).getState();

        // ARE WE CONNECTED TO THE NET
        if (info0 == connected || info0 == connecting || info1 == connecting
                || info1 == connected) {

            Log.d("Internet", "Connected");
            return true;
        } else if (info0 == disconnected || info1 == disconnected) {
            Log.d("Internet", "DisConnected");
            return false;
        }
        return false;
    }

答案 1 :(得分:0)

见下面的代码

    public static boolean checkConnection(Context context) {

    final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else
        return false;
}

答案 2 :(得分:0)

所以,它连接到Wi-Fi网络但没有互联网接入。正确?

尝试ping 8.8.8.8或google.com以了解是否有互联网访问权限。  This会帮助你。