Turns on hidden SSID if not set. - Android Wifi

Android examples for Wifi:Wifi SSID

Description

Turns on hidden SSID if not set.

Demo Code


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.net.InetAddress;
import java.util.List;

public class Main{
    private static final String TAG = WifiUtils.class.getSimpleName();
    public static Context sContext;
    private static WifiManager sWifiManager;
    /**// w  w w .j av a 2  s .c  o  m
     * Turns on hiddenSSID if not set.
     *
     * @param wrapper wifi configuration to check
     * @return true if hiddenSSID was set, false if already set
     */
    private static boolean turnOnHiddenSsid(WifiConfigurationWrapper wrapper) {
        try {
            if (wrapper == null || wrapper.getConfig().hiddenSSID) {
                return false;
            }

            wrapper.getConfig().hiddenSSID = true;
            setWifiConfig(wrapper, false);
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return true;
    }
    public static void setWifiConfig(
            WifiConfigurationWrapper wifiConfigWrapper, boolean deleteOthers)
            throws Exception {
        WifiManager wifiManager = getWifiManager();

        // this also updates an already existing config for the same network
        int networkId = wifiManager.addNetwork(wifiConfigWrapper
                .getConfig());
        if (networkId == -1) {
            Log.e(TAG, "Failed to add/update wifi config: "
                    + wifiConfigWrapper.getConfig().toString());
            return;
        }

        wifiManager.enableNetwork(networkId, false);

        if (deleteOthers) {
            deleteOtherNetworks(wifiManager, networkId);
        }
        wifiManager.saveConfiguration();
    }
    public static WifiManager getWifiManager() throws Exception {
        if (sWifiManager == null) {
            sWifiManager = (WifiManager) sContext
                    .getSystemService(Context.WIFI_SERVICE);
        }
        // TODO: throw if we can't use wifiManager (wpa_supplicant isn't ready/running)
        if (!sWifiManager.isWifiEnabled()) {
            sWifiManager.setWifiEnabled(true);
        }
        return sWifiManager;
    }
    public static void deleteOtherNetworks(WifiManager wifiManager,
            int networkId) {
        // Delete all other configs
        List<WifiConfiguration> configuredNetworks = wifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration conf : configuredNetworks) {
            if (conf.networkId != networkId) {
                wifiManager.removeNetwork(conf.networkId);
            }
        }
    }
}

Related Tutorials