title: Connecting to a WiFi network programatically
body: <p>I'm trying to make an app, and I'm having some problems I can't solve for now:</p>
  
  <p>My application has to connect to an specific AP with specified name and show the IP gateway. What I am trying to do is that when the app starts, it checks if the WiFi module is enabled. If it's not, then enable it and connect to the AP. If it's enabled, check if it's already connected to the correct AP, and if it's not, connect there.</p>
  
  <p>So, for now I did:</p>
  
  <p>Enable wifi part. It's a function called via AlertDialog named enableWifi() (<a href="https://stackoverflow.com/questions/5674333/android-how-to-enable-disable-wireless-from-an-application">How to enable/disable WiFi from an application?</a>)</p>
  
  <p>Setup WiFi network information and connect there. It's also a function called via AlertDialog named setupWiFi() (<a href="https://stackoverflow.com/questions/2140133/how-and-what-to-set-to-android-wificonfiguration-presharedkey-to-connect-to-the">How and what to set to Android WifiConfiguration.preSharedKey to connect to the WPA2 PSK WiFi network</a>)</p>
  
  <p>Get the IP Gateway. It's a function named setIP(). This writes de IP in EditText view. (<a href="https://stackoverflow.com/questions/5387036/how-to-get-gateway-and-subnet-mask-details-in-android-programmatically">Programmatically getting the gateway and subnet mask details</a>)</p>
  
  <p>There are two ways of connecting to the AP:</p>
  
  <p>1) Enable Wifi -> Connect to AP</p>
  
  <p>2) Connect to AP</p>
  
  <p>So here comes the problem: When I enable WiFi module, I should wait to finish enabling for starting to connect to the AP, and then wait to finish connection to retrieve the gateway IP. I don't know how to do those "wait" parts. What my app does now if I'm in 2) is connect to AP and get the gateway of the current network, which is still the old one and the one we don't want.</p>
  
  <p>I tried threads such as AsyncTask and Thread but couldn't make it work...</p>
  
  <p>Thanks for reading and I hope this is easy to solve!</p>
  
  <p>Kind regards,
  Raúl Suárez</p>