如何使用指定的SSID自动连接WiFi?

Tod*_*wok 6 java android android-wifi

有人可以帮我解决这个问题吗?

这是我的代码,并且mWifi.enableNetwork(netID, true)它无法启用网络,无法自动连接到指定的网络.所以我想知道我犯了什么错误?

    public class WifiConnActivity extends Activity {
    /** Called when the activity is first created. */
    final String tag = "WifiConn:...";
    EditText txt;
    WifiManager mWifi;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mWifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);

        txt = (EditText)findViewById(R.id.editText1);

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

                if (mWifi.startScan())  //scan now
                {
                    Log.d(tag, "startScan()");

                    List<ScanResult> sRet = mWifi.getScanResults();  //scan results.

                    for (int i=0; i<sRet.size(); i++)
                    {
                        ScanResult retS = sRet.get(i); 
                        txt.append("resT: " + retS.SSID +" " + retS.BSSID + "\n");
                        Log.d(tag, "resT: " + retS.SSID +" " + retS.BSSID);

                        if (retS.SSID.equalsIgnoreCase("TEST"))
                        {
                            txt.append("Found: " + retS.SSID +" " + retS.BSSID + "\n");

                            WifiConfiguration wc = new WifiConfiguration();

                            wc.SSID = "\""+retS.SSID+"\"";
                            wc.BSSID = retS.BSSID;
                            wc.status = WifiConfiguration.Status.ENABLED;
                            wc.hiddenSSID = true;

                            int netID = mWifi.addNetwork(wc); // add network
                            txt.append("addNetwork: "+ Integer.toString(netID) +"\n");

                            if(mWifi.enableNetwork(netID, true)) // enable network, but cannot work???????????
                            {
                                txt.append("enableNetwork: true\n");
                            }
                        }
                    }

                }
            }

        });      
    }
}
Run Code Online (Sandbox Code Playgroud)

QED*_*QED 2

我认为您需要将 a 添加WifiConfiguration.KeyMgmt到您的 WifiConfiguration 对象中。假设它是一个开放网络:

wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Run Code Online (Sandbox Code Playgroud)

另外,请谨慎假设扫描结果在退出调用后立即可用startScan()。在这种情况下,最好的选择是添加一个 BroadcastReceiverWifiManager.SCAN_RESULTS_AVAILABLE_ACTION并将所有代码添加到其中mWifi.getScanResults()mWifi.reconnect()一旦成功,您将需要添加一个调用enableNetwork()

至于初始化你的WifiConfiguration wc,如果你能考虑我在这里的帖子,我会很高兴。最后,另一个很好的答案在这里