3

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

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

上面的代码仅在可用时才Network有效!但是,我的设备有wifi和,当我同时使用上面两种类型的网络连接时,3G上面的代码总是返回!(当它返回时false我仍然可以使用)!我错过了什么?谢谢!google.comfalse

4

2 回答 2

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

于 2012-10-02T09:42:52.357 回答
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;
}
于 2012-10-02T09:26:09.073 回答