androidinternet-connection

How to test for active internet connection in android


I'm using this method to ping google server so I can check for active internet connection but I discovered that it doesn't work on all devices.

I've tried using other methods like HttpURLConnection and URLConnection but they all return false even when i'm connected.

Any ideas or solutions one that works on all devices.Thanks in advance.I'll post in succession what I've tried already.

Method 1:

public static Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 8.8.8.8");
        int returnVal = p1.waitFor();
        return (returnVal == 0);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

This one i've tried with locally and also with google servers and it yields perfect results.Problem is it doesn't work on all devices.

Method 2:

public boolean isConnected() {
    boolean connectivity;
    try {
        URL url = new URL("www.google.com");
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.connect();
        connectivity = true;
    } catch (Exception e) {
        connectivity = false;
    }
    return connectivity;
}

This one returns false always despite my connection being active.

Method 3:

public static boolean isInternetReachable() {
    try {
        //make a URL to a known source
        URL url = new URL("http://www.google.co.ke");

        //open a connection to that source
        HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();

        Object objData = urlConnect.getContent();

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

Same as this one.False value.

The last one was this class but it's also doing the same thing:

class TestInternet extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                connected = true;
                return connected;
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            connected = false;
            return connected;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            connected = false;
            return connected;
        }
        return connected;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) { // code if not connected
            AlertDialog.Builder builder = new AlertDialog.Builder(CtgActivity.this);
            builder.setMessage("An internet connection is required.");
            builder.setCancelable(false);

            builder.setPositiveButton(
                    "TRY AGAIN",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            new TestInternet().execute();
                        }
                    });


            AlertDialog alert11 = builder.create();
            alert11.show();
        } else { // code if connected
            Toast.makeText(CtgActivity.this,"Yes",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onPreExecute() {
        Toast.makeText(getBaseContext(),"Checking for internet",Toast.LENGTH_LONG).show();
        super.onPreExecute();
    }
}

I was going through SO to find anything I could but everything revolves around these.Please tell me if it's something I'm doing wrong or suggest a better workaround for it.It's the last step in my project.


Solution

  • Follow below code to check properly Internet is available or not as well as active or not.

       //I have taken dummy icon from server, so it may be removed in future. So you can place one small icon on server and then access your own URL.
    

    1. Specify Permission in manifest file, also make sure for marshmellwo runtime permission handle. As I am not going to show reuntime permission here.

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

    2. Check for Internet Availibility and the State as Active or Inactive.

            public class InternetDemo extends Activity
            {
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
    
                    checkInternetAvailibility();
                }
    
                public void checkInternetAvailibility()
                {
                    if(isInternetAvailable())
                    {
                        new IsInternetActive().execute();
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Internet Not Connected", Toast.LENGTH_LONG).show();
                    }
                }
    
                public boolean isInternetAvailable() {
                    try {
                        ConnectivityManager connectivityManager
                                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
                    } catch (Exception e) {
    
                        Log.e("isInternetAvailable:",e.toString());
                        return false;
                    }
                }
    
                class IsInternetActive extends AsyncTask<Void, Void, String>
                {
                    InputStream is = null;
                    String json = "Fail";
    
                    @Override
                    protected String doInBackground(Void... params) {
                        try {
                            URL strUrl = new URL("http://icons.iconarchive.com/icons/designbolts/handstitch-social/24/Android-icon.png");
                            //Here I have taken one android small icon from server, you can put your own icon on server and access your URL, otherwise icon may removed from another server.
    
                            URLConnection connection = strUrl.openConnection();
                            connection.setDoOutput(true);
                            is =  connection.getInputStream();
                            json = "Success";
    
                        } catch (Exception e) {
                            e.printStackTrace();
                            json = "Fail";
                        }
                        return json;
    
                    }
    
                    @Override
                    protected void onPostExecute(String result) {
                        if (result != null)
                        {
                           if(result.equals("Fail"))
                           {
                               Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
                           }
                           else
                           {
                               Toast.makeText(getApplicationContext(), "Internet Active " + result, Toast.LENGTH_LONG).show();
                           }
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
                        }
                    }
    
                    @Override
                    protected void onPreExecute() {
                        Toast.makeText(getBaseContext(),"Validating Internet",Toast.LENGTH_LONG).show();
                        super.onPreExecute();
                    }
                }
            }