How to auto connect a WiFi with specified SSID?

末鹿安然 提交于 2019-12-03 07:46:44
QED

I think you need to add a WifiConfiguration.KeyMgmt to your WifiConfiguration object. Assuming it's an open network:

wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

Also, be cautious in assuming that scan results are available immediately upon exit of your call to startScan(). The best bet in this case is to add a BroadcastReceiver on WifiManager.SCAN_RESULTS_AVAILABLE_ACTION and add to it all of your code from mWifi.getScanResults() forward. You will need to add a call to mWifi.reconnect() once you get enableNetwork() to succeed.

As for initializing your WifiConfiguration wc, I'd love it if you'd consider my post here. Finally, another good answer is here.

try adding remaining information about the network such as allowed ciphers, key Mangement scheme and the PSK (if you are using one)

Secondly check in the configured networks list first to make sure that you don't try to add another network with the same configuration as there is not point doing that.

As a recommendation don't startScan() and wait for it finish. Register for SCAN_RESULTS_AVAILABLE_ACTION and use a callback from the broadcast receiver to your activity to process those results.

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