android 连接指定wifi

连接指定wifi

/**
 * Created by grzh02 on 2018/9/3.
 */

public class WifiAutoConnector {

    private static final String TAG = WifiAutoConnector.class.getSimpleName();

    private WifiManager wifiManager;
    private IWifiConnectorListener mListener;

    public static final int WIFI_CIPHER_WPA = 3;
    public static final int WIFI_CIPHER_NOPASS = 2;
    public static final int WIFI_CIPHER_WEP = 1;


    // 构造函数
    public WifiAutoConnector(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    public void setConnectorListener(IWifiConnectorListener listener) {
        this.mListener = listener;
    }

    // 提供一个外部接口,传入要连接的无线网
    public void connect(String ssid, String password, int type) {
        ConnectManager cm = new ConnectManager(ssid, password, type);
        cm.connect();
    }

    // 查看以前是否也配置过这个网络
    private WifiConfiguration isExist(String SSID) {
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        if (existingConfigs != null) {
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                    return existingConfig;
                }
            }
        }
        return null;
    }

    private WifiConfiguration createWifiInfo(String SSID, String Password, int wifiCapabilities) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        // nopass
        if (wifiCapabilities == WIFI_CIPHER_NOPASS) {
            config.wepKeys[0] = "\"" + "\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wep
        if (wifiCapabilities == WIFI_CIPHER_WEP) {
            if (!TextUtils.isEmpty(Password)) {
                if (isHexWepKey(Password)) {
                    config.wepKeys[0] = Password;
                } else {
                    config.wepKeys[0] = "\"" + Password + "\"";
                }
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wpa
        if (wifiCapabilities == WIFI_CIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            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.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    // 打开wifi功能
    private boolean openWifi() {
        boolean bRet = true;
        if (!wifiManager.isWifiEnabled()) {
            bRet = wifiManager.setWifiEnabled(true);
        }
        return bRet;
    }


    class ConnectManager {
        private String ssid;

        private String password;

        private int type;

        public ConnectManager(String ssid, String password, int type) {
            this.ssid = ssid;
            this.password = password;
            this.type = type;
        }

        public void connect() {
            // 打开wifi
            boolean isOpen = openWifi();
            if (!isOpen) {
                mListener.onConnectorState(false, "");
                return;
            }

            wifiManager.disconnect();
            while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
                try {
                    // 为了避免程序一直while循环,让它睡个100毫秒检测……
                    Thread.sleep(300);
                } catch (InterruptedException ie) {
                }
            }

//            WifiConfiguration tempConfig = isExist(ssid);
//            if (tempConfig != null) {
//                int networkId = wifiManager.getConnectionInfo().getNetworkId();
//                boolean isForgot = wifiManager.removeNetwork(networkId);
//                if (!isForgot) {
//                    Log.i(TAG, "网络忘记不成功....");
//                }
//            } else {
//                Log.i(TAG, "该网络的配置不存在....");
//            }


            WifiConfiguration wifiConfig = createWifiInfo(ssid, password, type);
            if (wifiConfig == null) {
                Log.d(TAG, "wifiConfig is null!");
                return;
            }
            int netID = wifiManager.addNetwork(wifiConfig);
            boolean enabled = wifiManager.enableNetwork(netID, true);
            Log.e(TAG, "enable=" + enabled + " ssid = " + ssid);
            String tmpSsid = "\"" + ssid + "\"";
            boolean connected = wifiManager.reconnect() && tmpSsid.equals(CommonUtils.getWifiName());
            Log.d(TAG, "enableNetwork connected=" + connected);

            if (mListener != null) {
                mListener.onConnectorState(connected, NetUtils.getLocalIpAddress(App.getContext()));
            }
        }

    }

    private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
                return false;
            }
        }

        return true;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值