在Android中检查3G和W​​ifi的互联网连接

时间:2012-10-02 09:24:51

标签: android networking

有时,我必须在我的Android应用中检查互联网连接:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

上面的代码仅在一个Network可用时才有效!但是,我的设备有wifi3G,当我同时使用上述两种网络连接时,上面的代码始终返回false! (当它返回google.com时,我仍然可以使用false)!!我错过了什么?谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个

private boolean haveNetworkConnection() 
{
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) 
    {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

答案 1 :(得分:2)

这段代码怎么样?

        ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    // Check the current state of the Network Information
    if (networkInfo == null)
        return false;
    if (networkInfo.isConnected() == false)
        return false;
    if (networkInfo.isAvailable() == false)
        return false;
    return true;

请记住在应用程序清单文件中添加它:

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