Testing an application’s Internet connection

Asked

Viewed 9,199 times

10

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

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

Could someone help me check the internet before the app tries to consume the webservice?

  • Oops, I hope I help you: https://answall.com/questions/111898/identificar-tipo-de-conex%C3%A3o-3g-4g-e-ou-wifi

2 answers

9

This method validates if there is a connection.

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;
 }

While consuming the web service, you can add a Try catch and catch the execption Unknownhostexception and treat it.

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

6

First, don’t forget the Manifest permission. If not, your application won’t be able to connect.

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

Then, create a method somewhere of your choice 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 connection status.

if(isOnline()) { 
    //faz algo :)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.