startscan() has result after 10 min when phone get into idle state

纵然是瞬间 提交于 2019-12-20 04:35:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!