0

I have facing a problem regarding device is available on internet or not.Let me explain my query in brief with a example: I have test my application with a use case i.e I have on my router wifi but I unplug the Ethernet cable from my router and connect my device on wifi and by using following code:

private boolean checkConnection() {
    boolean connected = false;
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                & ni.isConnected() & ni.isAvailable()) {
                connected = true;
            }

        }
    }

    return connected;
}

I will get a Boolean flag for connectivity .This code return the device status of switch means my device is connected with WiFi or not but I will not getting any response from the server or host,So I need to check the internet feasibility on my device or not .Please some one help me for the same.I have tried many goggling approaches or methodology but failed in success.

Thanks in advance.

erikvimz
  • 5,256
  • 6
  • 44
  • 60

2 Answers2

0

If you need to check if connection actually provides internet, you can try pinging some remote host - google, for example: How to Ping External IP from Java Android

Community
  • 1
  • 1
Jehy
  • 4,729
  • 1
  • 38
  • 55
  • Thx for your reply but its not suited my need when i will test this code with my use case its also getting failed. – Mohd Ahsan Jun 01 '16 at 10:13
  • my use case is wifi router is not connected to internet but my device is connected to the router and showing that my device is connected to the device wifi and it will also taking too long time like 30 -40 second to through the exception unknown-host and its very bad for user experience i just want a solution with in 3-4 second,Do you have any suggestion for the same – Mohd Ahsan Jun 01 '16 at 10:16
  • use retrofit or loopj library they have handled all that things you will get error code when you will not get and data traffic from connection. – Pradeep Deshmukh Jun 01 '16 at 11:27
  • @MohdAhsan - if You have no internet connection, but yet physically connected to the router (which is actually a device that belongs to network layer of ISO/OSI model) you can try to ping the router. – Tomasz Dzieniak Jun 01 '16 at 12:00
  • @MohdAhsan Yeah, name resolve can take long time if it is failing. To skip it, you can ping IP address, not domain name. For example, try pinging google's ip `8.8.8.8` - it should take several seconds to accomplish, just as you want. – Jehy Jun 01 '16 at 12:46
0
      On button click 
        if(isInternetON(MainActivity.this)){
        mMyDownloadTask = new MyDownloadTask();
        delayCancel = new DelayCancel(mMyDownloadTask);
        handler.postDelayed(delayCancel,3*1000);
        mMyDownloadTask.execute();



        }



  public static class MyDownloadTask extends AsyncTask<Boolean,Void,Boolean> {

        public MyDownloadTask() {

        }

        protected Boolean doInBackground(Boolean... params) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//              connection.setRequestMethod("Head");
//              connection.setConnectTimeout(2000);
                connection.connect();

                int code = connection.getResponseCode();
                Log.e(TAG, "code : " + code);
                if (code == 200) {
                    ThreadActivity.isAviliable = true;
                    MainActivity.value = "true";
                    return true;

                } else {
                    ThreadActivity.isAviliable = false;
                    MainActivity.value = "false";
                    return false;

                }

            } catch (Exception e) {
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
                e.printStackTrace();
                return false;
            }

        }

        protected void onPostExecute(Boolean result) {
            // dismiss progress dialog and update ui
            Log.e(TAG,"result "+result);
            if(result){
                ThreadActivity.isAviliable = true;
                MainActivity.value = "true";
            }else{
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
            }

        }
    }
    public static class DelayCancel implements Runnable{
        private AsyncTask task;

        public DelayCancel(AsyncTask task) {
            this.task = task;

        }

        @Override
        public void run() {
            Log.e(TAG, "Running.....");
            if (task.getStatus() == AsyncTask.Status.RUNNING) {
                task.cancel(true);
                Log.e(TAG, "Cancel 1.....");
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
            }
            if (task.getStatus() == AsyncTask.Status.PENDING){
                task.cancel(true);
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
                Log.e(TAG, "Cancel 2.....");
            }
        }
    }

    public static boolean isInternetON(Context ctx){

        ConnectivityManager cm =(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

       /* Log.e("Common Class","activeNetwork.getState()"+activeNetwork.getState());
        Log.e("Common Class","activeNetwork.isAvailable()"+activeNetwork.isAvailable());
        Log.e("Common Class","activeNetwork.getReason()"+activeNetwork.getReason());
        Log.e("Common Class","activeNetwork.getExtraInfo()"+activeNetwork.getExtraInfo());
        Log.e("Common Class","activeNetwork.describeContents()"+activeNetwork.describeContents());
        Log.e("Common Class","activeNetwork.isConnectedOrConnecting()"+activeNetwork.isConnectedOrConnecting());
        Log.e("Common Class","activeNetwork.isFailover()"+activeNetwork.isFailover());*/

        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting() && activeNetwork.isAvailable();

        return isConnected;
    }