Connection handling - java.net.ConnectException: Failed to connect to / IP

0

Before requesting any requests, I'll make a connection test:

ConnectivityManager conexao;


private boolean verificaConexao() {

    this.conexao = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = this.conexao.getActiveNetworkInfo();

    if ((netInfo != null) && (netInfo.isConnectedOrConnecting()) && (netInfo.isAvailable())) {
        Log.i("lgg", "conectado");
        return true;
    } else {
        Log.i("lgg", "sem conexão");
        return false;
    }

}

I have 2 IP's of output, so I created a Switch that I make the exchange, so I have 4 tests:

  • Airplane mode + IP 1 = return: false;
  • Airplane mode + IP 2 = return: false;
  • Wifi + IP 1 = return true;
  • Wifi + IP 2 = no return ( java.net.ConnectException: Failed to connect to /IP2 )
  • IP 2, it really will not respond depending on the network the device is connected to.

    I would like to know how to handle this error to return false ?

        
    asked by anonymous 02.03.2018 / 11:51

    1 answer

    0

    You can catch the ConnectException and then return false. How to use a try / catch directly in the method CheckConnection () results in compilation error that ConnectException is not thrown, you can work around putting the part of the code that throws the exception inside a method and declare that it throws ConnectException ():

    private boolean verificaConexao() {
        try {
            NetworkInfo netInfo = getNetworkInfo();
            if ((netInfo != null) && (netInfo.isConnectedOrConnecting()) && (netInfo.isAvailable())) {
                return true;
            } else {
                return false;
            }
        } catch (ConnectException ce) {
            Log.e(ce);
        }
    }
    
    NetworkInfo getNetworkInfo() throws ConnectException {
        conexao = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return this.conexao.getActiveNetworkInfo();
    }
    
        
    02.03.2018 / 17:40