connect To Wifi Network - Android android.net.wifi

Android examples for android.net.wifi:Wifi Connection

Description

connect To Wifi Network

Demo Code

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

public class Main {

  public static boolean connectToWifiNetwork(Context context, String networkSSID, String networkPass, String security) {

    WifiConfiguration conf = new WifiConfiguration();

    conf.SSID = "\"" + networkSSID + "\"";

    if (security.equals("OPEN")) {
      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }//from  w w  w  . j  av a  2 s  .c  om

    else if (security.equals("WEP")) {
      conf.wepKeys[0] = "\"" + networkPass + "\"";
      conf.wepTxKeyIndex = 0;
      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    }

    else {
      conf.preSharedKey = "\"" + networkPass + "\"";
    }

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int networkId = wifiManager.addNetwork(conf);

    boolean result = wifiManager.enableNetwork(networkId, true);

    wifiManager.saveConfiguration();

    return result;
  }

}

Related Tutorials