1

I am trying to scan wifi networks every 2 minutes. I am using service for that. When the phone is "active" or "in use" after startscan() called I get SCAN_RESULTS_AVAILABLE_ACTION in 6 sec. So i can scan for wifis periodically. But after the phone has not been touched by anyone for a certain time (10 min) startscan() stops "working" and only after 10 min getting result. Anybody experienced this?

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
laplasz
  • 3,359
  • 1
  • 29
  • 40

1 Answers1

3

According to this I have found the solution - this is because the Wifi sleep policy. You can set your wifi device never goes to sleep with this:

Settings.System.putInt(getContentResolver(),
              Settings.System.WIFI_SLEEP_POLICY, 
              Settings.System.WIFI_SLEEP_POLICY_NEVER);

Be sure, that you added this permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

the scanning period will be 5-15s - and this is automatic - you dont need to call startscan(). more info about Android scanning process can be found here.
Edit:
maybe this is even better solution if you only want to scan for hotspots:
WIFI_MODE_SCAN_ONLY - it can be activated by:

WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiLock wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY , "MyWifiLock");
if(!wifiLock.isHeld()){
    wifiLock.acquire();
}

dont forget to release it, more info about WifiLock here
also define this permission:

<uses-permission android:name="android.permission.WAKE_LOCK"/>

Edit2 this works as well:
you can enable, and disable wifi periodically:

WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(wm.isWifiEnabled() == false) {
    wm.setWifiEnabled(true);
}

then scan after your broadcastreceiver gets the action containing WIFI_STATE_ENABLED extra

Community
  • 1
  • 1
laplasz
  • 3,359
  • 1
  • 29
  • 40
  • +1 nice - see my question on `getScanResults();` [here](http://stackoverflow.com/questions/16137268/wifimanager-getscanresults-clarifications-automatic-scans-sleep-etc). Also - suppose you enable wireless, then you want to redisable it after scanning - what if the user had enabled it while you were scanning (so you should not disable it) ? Is there a way to know ? – Mr_and_Mrs_D Apr 21 '13 at 23:29