Search code examples
androidapplication-settings

How to check internet access is enabled in android?


Iam trying to create an application that connect to a webserver and retricve data, i want to do some functions

  1. when i click my application, first it check whether the internet access is enabled? if it is enabled it start the application , else open the internet access settings..after that it redirect to my application....
  2. when the application is connecting to web-server, connection is timed out after a specific time if the connection is not success.

Solution

  • In an application of mine, I have a class defined like this:

        public class ConnectionDetector {
    
            private Context _context;
    
            public ConnectionDetector(Context context){
                this._context = context;
            }
    
            /**
             * Checking for all possible internet providers
             * **/
            public boolean isConnectingToInternet(){
                ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
                  if (connectivity != null)
                  {
                      NetworkInfo[] info = connectivity.getAllNetworkInfo();
                      if (info != null)
                          for (int i = 0; i < info.length; i++)
                              if (info[i].getState() == NetworkInfo.State.CONNECTED)
                              {
                                  return true;
                              }
    
                  }
                  return false;
            }
        }
    

    And in the Activity that I need to check the connectivity status, I use this:

        // DEFINE THIS AS A GLOBAL VARIABLE
        AlertDialogManager alert = new AlertDialogManager();
    

    In the onCreate():

        ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
    

    Oh. Almost forgot. If you also need to re-direct the user to the settings panel to activate Internet, you can use an Intent like this:

    You could prompt the user in the AlertDialog and let them choose if they want to. If yes, run this piece of code.

    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
    startActivity(intent);
    

    EDIT:

    I missed the obvious (Commonsware pointed that one out in his comment).

    You will need to add the ACCESS_NETWORK_STATE permission to your Manifest file.

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