Code example for WifiManager

Methods: addNetworkdisconnectenableNetworkreconnect

4
     * Function to disconnect from the currently connected WiFi AP. 
     * @return true  if disconnection succeeded 
     * 				 false if disconnection failed 
     */ 
    public boolean disconnectFromWifi() { 
        return (wifiMgr.disconnect());
    } 
 
    /** 
     * Function to connect to a selected network 
     * @param networkSSID         network SSID name 
     * @param	networkPassword     network password 
     * @param networkId           network ID from WifiManager 
     * @param SecurityProtocol    network security protocol 
     * @return true  if connection to selected network succeeded 
     * 				 false if connection to selected network failed 
     */ 
    public boolean connectToSelectedNetwork(String networkSSID, String networkPassword) {
        int networkId;
        int SecurityProtocol = WEP;
 
        // Clear wifi configuration variable 
        clearWifiConfig(); 
 
        // Sets network SSID name on wifiConf  
        wifiConf.SSID = "\"" + networkSSID + "\"";
        Log.d(TAG, "SSID Received: " + wifiConf.SSID);
        switch(SecurityProtocol) {
            // WEP "security". 
            case WEP:
                wifiConf.wepKeys[0] = "\"" + networkPassword + "\""; 
                wifiConf.wepTxKeyIndex = 0;
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break; 
 
                // WAP security. We have to set preSharedKey. 
            case WAP:
                wifiConf.preSharedKey = "\""+ networkPassword +"\"";
                break; 
 
                // Network without security. 
            case OPEN_NETWORK:
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break; 
        } 
 
        // Add WiFi configuration to list of recognizable networks 
        if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
            Log.d("TAG", "Failed to add network configuration!");
            return false; 
        } 
 
        // Disconnect from current WiFi connection 
        if (!disconnectFromWifi()) { 
            Log.d("TAG", "Failed to disconnect from network!");
            return false; 
        } 
 
        // Enable network to be connected 
        if (!wifiMgr.enableNetwork(networkId, true)) {
            Log.d("TAG", "Failed to enable network!");
            return false; 
        } 
 
        // Connect to network 
        if (!wifiMgr.reconnect()) {
            Log.d("TAG", "Failed to connect!");
            return false; 
        } 
 
        return true;