0

I have written some code to ping Google to check Internet connectivity.

The app works except that it takes a lot of time to send back the response (up-to 1 min). This happens especially when Mobile Network is turned ON but there is no Internet connectivity

I would appreciate it if you would help me find a solution

The layout consists of just a Button. Following is my Java code:

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main_activity_final);
  Button b1=(Button)findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //Thread t = new Thread(new Runnable() {
              //  public void run() {
                    //pingCheck = isURLReachable(getApplicationContext());
                    new MyTask().execute();
                    //}
              //});
              //t.start(); 
            }
        });
  }

  private class MyTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
      try {
        URL url = new URL("http://google.com");   // Change to "http://google.com" for www  test.
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setConnectTimeout(10*500);          // 10 s.
        urlc.connect();

        if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
           Log.wtf("Connection", "Success !");
           return true;
        } else {
           return false;
        }
      } catch (MalformedURLException e1) {
        return false;
      } catch (IOException e) {
        return false;
      }
    }

    @Override
    protected void onPostExecute(Boolean result) {
      boolean bResponse = result;
      if (bResponse==true) {
        Toast.makeText(MainActivityFinal.this, "Network  is available", Toast.LENGTH_LONG).show();      
      } else {           
        Toast.makeText(MainActivityFinal.this, "Network  is not available", Toast.LENGTH_LONG).show();
      }                  
    }               
  }

Thank you.

swiftBoy
  • 35,607
  • 26
  • 136
  • 135

1 Answers1

0

I suggest to add urlc.setReadTimeout(10*500); below urlc.setConnectTimeout(10*500);.

By the way, it's a timeout of 5 seconds and not ten.

mm759
  • 1,404
  • 1
  • 9
  • 7