问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/14862018/startscan-has-result-after-10-min-when-phone-get-into-idle-state