-1

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

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

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

4 回答 4

1
     if (con_manager.getActiveNetworkInfo() != null && 
         con_manager.getActiveNetworkInfo().isAvailable()
              && con_manager.getActiveNetworkInfo().isConnected())
                  {   }
于 2013-09-21T11:41:36.423 回答
0

尝试这个

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

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

   // No Network detected

        //return;
    }
于 2013-09-03T12:02:54.737 回答
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;
}
于 2013-09-03T11:58:49.103 回答
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;
}
于 2013-09-03T11:59:32.213 回答