connect To Network by user name and password - Android Phone

Android examples for Phone:Bluetooth

Description

connect To Network by user name and password

Demo Code


//package com.java2s;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

public class Main {
    public static boolean connectToNetwork(Context context,
            String username, String password) {
        boolean status = false;
        try {/* ww w  .j a  v a  2 s.  c om*/
            WifiManager wifi = (WifiManager) context
                    .getSystemService(context.WIFI_SERVICE);

            if (!wifi.isWifiEnabled()) {
                wifi.setWifiEnabled(true);
                Thread.sleep(3000);
            }

            WifiConfiguration netConfig = new WifiConfiguration();
            netConfig.SSID = "\"" + username + "\"";
            netConfig.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            netConfig.allowedKeyManagement
                    .set(WifiConfiguration.KeyMgmt.WPA_PSK);
            netConfig.preSharedKey = "\"" + password + "\"";
            netConfig.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.TKIP);

            int netId = wifi.addNetwork(netConfig);
            status = wifi.enableNetwork(netId, true);
        } catch (Exception e) {
            status = false;
            e.printStackTrace();
        }

        return status;
    }
}

Related Tutorials