title: How to Listen host url for detect active or inactive in Android
body: <p>I am developing an mobile application . I have an rectangle on screen. If my host (www.myhost.com) is alive then rectange is green.But there is no connection to my host , then rectange is red.I have an AsycTask class for listening host continuously.My code is </p>
  
  <pre><code>    public class ServerPing extends AsyncTask&lt;Void, Void, Void&gt; {
      boolean isConnected = false;
      boolean isstop=false;
  
      @Override
      protected Void doInBackground(Void... params) {
          return isOnline();
      } 
  
  
      private  Void isOnline() {
  
          while (!isstop){
          try{
              // Thread.sleep(5000);
              URL url = new URL("http://myhost.com");
                  HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
              // urlc.setRequestMethod("HEAD");
                  urlc.setConnectTimeout(3000);
                  urlc.connect();
  
                  if (urlc.getResponseCode()==200) {
  
                      if(!isConnected) {
                          isConnected=true;
                          ...Notify(true); // Notify Screen is green
                      } 
  
  
  
                  } 
  
                  else {
                      if(isConnected) 
                      {
                          isConnected=false;
                              ...Notify(false); // Notify Screen is red
                      }
                  } 
  
  
              urlc.disconnect();
  
          }catch(Exception e) {
  
              if(isConnected) {
                  isConnected=false;
                  ...Notify(false); // Notify Screen is red
              }
  
          }  
  
  
  
  
      }
          return null;
  
      }
  
  
  
  
  }
  </code></pre>
  
  <p>This code blocks well. But my question is ; This operation consume more CPU . Is there any proper way to detect server is active or inactive.</p>