问题
I would like to connect to WiFi network programmatically.
Here is my code:
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + ssid + "\"";
config.preSharedKey = "\""+ key +"\"";
int netId = wifiManager.addNetwork(config);
wifiManager.saveConfiguration();
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
When I have wifi enabled on my phone, it works as expected, but the problem is, when wifi is disabled. In this case the only result is enabling wifi adapter, but not connecting to the network. It seems like enabling takes to long so it won't get connected. Another strange thing to me is that wifiManager.getConfiguredNetworks()
returns null. Do you know how to fix that?
Thank you
回答1:
It seems like enabling takes to long so it won't get connected.
Yes. This is because enabling of the network is done async, it happens in parallel, and doesn't occur immediately. Here are two possible solutions to your problem:
1) This is the easiest solution, but not the best. Loop as described by another user checking for the scan results to come in. However, you should add a sleep of some sort between every cycle of the loop. I.E. you want to wait for 1ms, so as to not eat up all the CPU resources. I am not sure how to do this in Android off the top of my head. There is another problem with this method. If u are in the GUI thread, you will block all GUI events this way, as you wait for the connection to be established.
2) This is the proper solution. You can register for broadcast events after the network connection has been established. Then you will get an event when it finishes. From this event you can finish performing whatever operations are needed.
Sorry for the rushed answer. I am not an Android pro, so I can't explain the details as to how to do this off the top of my head, but I thought I would at least point you in the right direction.
回答2:
Actually if you connect WiFi more than one time it will solve your issue.
One other thing I see if my WiFi is enabled and I connect to a specific WiFi network then it's working.
One other thing when I switch from mobile network to a specific WiFi network then it gives an unstable connection ..for this problem I connect WiFi through a specific WiFi network and then forget the network after a 3 second delay I again connect. Then it works properly.
I use this code for connecting to WiFi.
And for delay and for got WiFi network I use this code... .......
{
wifi(SSID,PASS);
final Handler handler = new Handler();
handler.postDelayed(
new Runnable()
{
Override public void run() { forgot(); }
}, 3000);
final Handler handler1 = new Handler();
handler1.postDelayed(
new Runnable()
{
Override public void run() {wifi(SSID,PASS); }
}, 3000);
}
来源:https://stackoverflow.com/questions/15253982/android-connect-to-wifi-programmatically