title: Android Internet Connection Broadcast Recevier
body: <p>My app is running in the background (as a Service) and needs to be connected to a remote server all the time to receive and send messages.</p>
  
  <p>This Service runs a Thread which manage the connection to the server (with Socket)</p>
  
  <p>i'm trying to write an internet connection Broadcast Receiver which will run every time the internet state is changed and check if the state is connected of disconnected.</p>
  
  <p>my problem is as follow: when i'm connected to Wi-Fi network the Broadcast Receiver Intent is fired few times which in all of them the state of the internet connection is true (with no disconnection between every fire, which means i have few new Threads using the Socket to connect the server.</p>
  
  <p>How can i make sure i'm getting the state of the internet right, and by right i mean that the .isConnected() method will return if and only if the connection is connected ?</p>
  
  <p>this is my code:</p>
  
  <pre><code>public void onReceive(Context context, Intent intent) 
  {       
      action = intent.getAction();
      app = (AppVariables) context.getApplicationContext();       
      if (app.isApplicationInitilized())
      {   
          if (action.equals(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)))
          {
              networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
              if (networkInfo.isConnected())
                  app.getServerConnectionManager().startServer();
          }
          else if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
          {
              networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);                
              if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI &amp;&amp; !networkInfo.isConnected())
                  app.getServerConnectionManager().stopServer(false);
              else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE &amp;&amp; !networkInfo.isConnected())
                  app.getServerConnectionManager().stopServer(false);
              else
                  app.getServerConnectionManager().startServer();
          }           
      }       
  }
  </code></pre>