failed to connect to specific WiFi in android programmatically

北城余情 提交于 2019-12-23 15:49:08

问题


I'm using the following code to detect and connect to specific WiFi ssid when I press a button in android. Below is the code. Any help will be appreciated.


ssid :- "myHotspot" & password:- "12345678"


 Button b1 = (Button) findViewById(R.id.button); <br>
        b1.setOnClickListener(new View.OnClickListener() {
            <br><br>@Override
            <br>public void onClick(View v) {

                wifiConfiguration.SSID = "\"myHotspot\"";
                wifiConfiguration.preSharedKey ="\"12345678\"";
                WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

                int netId = wifiManager.updateNetwork(wifiConfiguration);
               if (wifiManager.isWifiEnabled()) { //---wifi is turned on---
                    //---disconnect it first---
                    wifiManager.disconnect();

                } else { //---wifi is turned off---
                    //---turn on wifi---

                    wifiManager.setWifiEnabled(true);
                }
                wifiManager.enableNetwork(netId, true);
                wifiManager.reconnect();

            }
        });



The main problem I'm getting is that my phone gets connected to the ssid and after 2-3 seconds it loses the connection and gets connected to my home Wifi router (which has internet connectivity)


Note:- The ssid I'm trying to connect is just a local hotspot without any internet connection.
and if I try with "addNetwork(wifiConfiguration)" it creates multiple networks of the same name. so Now how do I resolve this ?!


回答1:


I think the problem here is you try to enableNetwork immediately after the call to wifiManager.setWifiEnabled(true). Generally, switching on wifi will take 5-10 seconds depending on the device, until then any call to wifiManager.enableNetwork will be lost. Hence, your call to connect to the desired network is getting lost and as soon as the wifi is switched on, your device connects to the last network it remembers.

Try to create a loop where you keep checking if wifiManager.isWifiEnabled() == true and keep looping until it returns true (with Thread.sleep() obviously and doing this in an AsyncTask or separate Thread). Only after that try to call enableNetwork.



来源:https://stackoverflow.com/questions/35145831/failed-to-connect-to-specific-wifi-in-android-programmatically

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