set Wifi Enabled by SSID, shared key - Android android.net.wifi

Android examples for android.net.wifi:Wifi SSID

Description

set Wifi Enabled by SSID, shared key

Demo Code

import java.lang.reflect.Method;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public class Main {

  private final static String TAG = "WifiUtils";

  public static boolean setWifiApEnabled(WifiManager wifiManager, String ssid, String sharedKey, boolean enable) {
    if (enable && wifiManager.isWifiEnabled()) {
      wifiManager.setWifiEnabled(false);
    }/*w  ww .j  a v  a 2 s . co m*/
    boolean result = false;
    try {
      WifiConfiguration config = new WifiConfiguration();
      config.SSID = ssid;
      config.preSharedKey = sharedKey;
      config.hiddenSSID = true;
      config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
      config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
      config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
      config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
      config.status = WifiConfiguration.Status.ENABLED;
      Method method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
      result = (Boolean) method.invoke(wifiManager, config, enable);
      Log.d(TAG, "setWifiApEnabled result= " + result);
    } catch (Exception e) {
      Log.d(TAG, "InvocationTargetException e:" + e.toString());
    }
    return result;
  }

}

Related Tutorials