Search code examples
androidandroid-wifiandroid-networkingandroid-internet

How to determine the network unavailability in android


I want to show alert that connection not available in my android application.

I am calling some rest request in my application. To check this network unavailability scenario I manually disconnect my wifi in my laptop (I am testing in simulator) .

Code where I call service is here

resp = client.execute(httpPostRequest);

and here I am catching exception

catch (IllegalStateException e) {
            //assertTrue(e.getLocalizedMessage(), false);
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            //assertTrue(e.getLocalizedMessage(), false);
            e.printStackTrace();
        } catch (IOException e) {
            //assertTrue(e.getLocalizedMessage(), false);
            e.printStackTrace();
        }

and when I get exception I try to get the status of the device network connection with this function

public boolean IsInternetConnectted()
    {
        ConnectivityManager conMgr =  (ConnectivityManager)this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
        conMgr = null;
        if (i == null)
            return false;
        if (!i.isConnected())
            return false;
        if (!i.isAvailable())
            return false;
        return true;        
    }

even if wi-fi is disconnected my simulator return true from this function.

How to resolve this situaltion??


Solution

  • I Found that same error in my Emulator... But Try your Code on Mobile Device this code Run Perfectly and not coming any error in real Device...