Test an application's internet connection

10

I have an app that connects to webservice but the problem is that when I get 3G, it gives error. When the connection is good, with a wi-fi for example it works perfectly.

I have some algorithms that test the connection, but everyone validates only if it is connected, and sometimes 3G has a network but does not connect to the internet, generating an error in the app.

Can anyone help me check the internet before the app tries to consume the webservice ?

    
asked by anonymous 18.08.2014 / 15:26

2 answers

9

This method validates if a connection exists.

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

During consumption to the web service, you can add a try catch and get the exection UnknownHostException and treat it.

  try {
    //seu código
  } catch(UnknownHostException e) {
   // trata o erro de conexão.
  }
    
18.08.2014 / 16:58
6

First, do not forget the permission on Manifest. If not, your application will not be able to connect.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Then, create a method in some place of your preference and where it makes sense in your application.

public boolean isOnline() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return manager.getActiveNetworkInfo() != null && 
       manager.getActiveNetworkInfo().isConnectedOrConnecting();
}

A basic "if" returns the status of the connection.

if(isOnline()) { 
    //faz algo :)
}
    
19.08.2014 / 01:42