0

I'm working on a project which need to connect to a Wi-Fi in a background service, the service running when the device is screen off. The connecting code is like below:

    public boolean connect_android(String ssid) {
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    boolean find = false;
    for( WifiConfiguration i : list ) {
        if(i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
             wifiManager.enableNetwork(i.networkId, true);
             wifiManager.reconnect();
             find = true;
             break;
        }           
     }

while after the connecting code is executed in the background running service, the device never connect to the Wi-Fi successfully until the screen is turned on. I logged the supplicant state, it is in complete state. As the google docs says:

This state indicates that the supplicant has completed its processing for the association phase and that data connection is fully configured. Note, however, that there may not be any IP address associated with the connection yet. Typically, a DHCP request needs to be sent at this point to obtain an address.

So can i come to the conclusion that, when the screen is turned on, a DHCP request is send the device receives an IP and the connection is complete successfully. But who is in charge of sending the DHCP, the wpa_supplicant or Android framework, is there any docs about this? How can i connect to a Wi-Fi AP without turn on the screen? Thanks in advance!

SalutonMondo
  • 629
  • 9
  • 17
  • not quite an answer but have you tried applying a cpu wakelock to the service until it has an ip address and then release it? – Burrito Mar 23 '15 at 02:52
  • Thanks Burrito. Yes i tried use PowerManager.WakeLock, lock before connecting code, and release after device get IP. it works on one testing AP but failed on the others AP. quite strange. – SalutonMondo Mar 23 '15 at 03:28
  • did you use a combination of wifi lock and cpu wakelock? reference for wifi lock if you havent http://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html – Burrito Mar 23 '15 at 03:30
  • i tried but still no luck. – SalutonMondo Mar 23 '15 at 04:25

1 Answers1

1

Maybe because your device use feature turn of wifi when screen of (Settings -> Wireless and network -> WiFi settings -> (menu button) Advanced -> Wifi sleep policy) Your app will cannot connect to network