方法总是返回“true”值

时间:2013-09-03 11:56:51

标签: android connection

为什么这个方法总是返回“true”值?

(连接状态和未连接状态!)

public void onClick(View v)
        {

            if(checkInternetConnection(ctx))
            {
                Toast.makeText(MainActivity.this, "Online", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Offline", Toast.LENGTH_SHORT).show();
            }
        }

/////////////////////////////////////////////// ///////////// checkInternetConnection //////////////////////////////////// /

public boolean checkInternetConnection(Context cntx) 
    {

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

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

4 个答案:

答案 0 :(得分:1)

     if (con_manager.getActiveNetworkInfo() != null && 
         con_manager.getActiveNetworkInfo().isAvailable()
              && con_manager.getActiveNetworkInfo().isConnected())
                  {   }

答案 1 :(得分:0)

尝试使用以下代码:

    public static boolean IsNetConnected() {
    boolean NetConnected = false;
    try {
        ConnectivityManager connectivity = (ConnectivityManager) m_context
            .getSystemService(m_context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            NetConnected = false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetConnected = true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        NetConnected = false;
    }
    return NetConnected;
}

答案 2 :(得分:0)

试试这个。

public static boolean isOnline(Activity con) {
    ConnectivityManager cm = (ConnectivityManager) con
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

答案 3 :(得分:0)

试试这个

    ConnectivityManager connectivityManager =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();

    if (info == null ||
            !connectivityManager.getBackgroundDataSetting()) {

   // No Network detected

        //return;
    }