How to automatically connect WiFi with the specified SSID?

Can some body help me solve this problem?

Here is my code, but mWifi.enableNetwork(netID, true)it cannot turn on the network and cannot automatically connect to the specified network. So I want to know where I was wrong?

    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");
                            }
                        }
                    }

                }
            }

        });      
    }
}
+5
source share
2 answers

I think you need to add WifiConfiguration.KeyMgmtWifiConfiguration to your object. Assuming this is an open network:

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

, , , startScan(). BroadcastReceiver WifiManager.SCAN_RESULTS_AVAILABLE_ACTION mWifi.getScanResults() . mWifi.reconnect() enableNetwork().

WifiConfiguration wc, , . , .

+2

, ​​ , Mangement PSK ( )

-, , , , .

Scan() . SCAN_RESULTS_AVAILABLE_ACTION .

0

All Articles