ADT中的ConnectivityManager和/或NetworkInfo中的返回值 - Android

时间:2013-09-01 08:20:37

标签: android connectivity eclipse-adt

当我使用下面的代码显示我的连接状态时,“if”条件总是返回“true”,除非我把“netinfo”等于“null”。

问题出在哪里?

public boolean isConnectedToInternet()
{   
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if ( netInfo.isConnectedOrConnecting())
        {
            Toast.makeText(this, "On",Toast.LENGTH_LONG).show();
            Log.i("NewsList", "Internet Connection found.");
            return true;
        }

    Toast.makeText(this, "Off",Toast.LENGTH_LONG).show();
    return false;
}

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:

<强> DetectConnection.class:

public class DetectConnection {
    /*
     * Checking internet connection
     */
    public static boolean checkInternetConnection(Context context) {

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

        if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

从其他活动检查互联网:

if (DetectConnection.checkInternetConnection(this)) {
        //do something
}