2

I am using isConnected() method to test Internet is working or not, However, When Mobile data is on but net is not working (happens when travelling) or Wifi is on but not connected to internet, the method returns true and my app crashes.

I did some finding and found that I need to ping Google also so I tried using internetConnectionAvailable(1000). Even if Internet is working fine, this method sometimes return false. Can anybody help me with a better solution?

 //Check device has Internet connection
    public boolean isConnected()    {
        ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else    {
            //Custom Toast method
            showToast("Unable to connect to Internet !");
            return false;
        }   
    }

//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
        InetAddress inetAddress = null;
        try {
            Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
                @Override
                public InetAddress call() {
                    try {

                        return InetAddress.getByName("www.google.com");
                    } catch (UnknownHostException e) {
                        return null;
                    }
                }
            });
            inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
            future.cancel(true);
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
        } catch (TimeoutException e) {
        }
        Log.e("Google",String.valueOf(inetAddress));
        return inetAddress!=null && !inetAddress.equals("");
    }
Rohit Sawant
  • 21
  • 1
  • 2
  • Have a look at this: http://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android and don't forget about permissions. – Parviz Sattorov Jan 18 '16 at 07:30
  • @Rohit you need to ping manually and see the response it it has 200 then you are good to go. Sample reference here http://crunchify.com/how-to-get-ping-status-of-any-http-end-point-in-java/ – silentsudo Jan 18 '16 at 08:34
  • Parviz Sattorov: Thanx. I have already declared the required permissions in Manifest. – Rohit Sawant Jan 18 '16 at 08:35

1 Answers1

0

Check whether the internet is connected/not... If yes androidTask() is called.

 if (haveNetworkConnection()) {
                new androidTask().execute();
            } else {
                Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
            }  

Called method of haveNetworkConnection():

 public boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

Method contains HTTP request:

 class androidTask extends AsyncTask<Void, Void, String> {
        String BASE_URL = http://abc.def.com/";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            HttpURLConnection con = null;
            InputStream is = null;

            hashMapPost.put("report", "users");

            try {
                con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.connect();
                OutputStream os = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(hashMapPost));
                writer.flush();
                writer.close();
                os.close();
                buffer = new StringBuffer();
                int responseCode = con.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    is = con.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while ((line = br.readLine()) != null)
                        buffer.append(line).append("\r\n");
                    is.close();
                }
                con.disconnect();
                return buffer.toString();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Throwable t) {
                }
                try {
                    if (con != null) {
                        con.disconnect();
                    }
                } catch (Throwable t) {
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        }
    }
Parama Sudha
  • 2,583
  • 3
  • 29
  • 48