安卓应用内连接wifi

2022-07-22  本文已影响0人  Ocean_e553

1.连接wifi (暂测试 wpa 加密方式正常)

public void connect() {

        WifiManager wifiManager = (WifiManager) context.getSystemService(Service.WIFI_SERVICE);
        String wifiName = "wifi-name";
        String wifiPassword = "wifi-password";

        List<ScanResult> list = wifiManager.getScanResults();
        ScanResult targetResult = null;
        for (ScanResult result: list) {
            if (result.SSID.equals(wifiName)) {
                targetResult = result;
                break;
            }
        }

        if (targetResult == null) {
            Toast.makeText(context, "没有找到WIFI", Toast.LENGTH_SHORT).show();
            return;
        }

        String cap = targetResult.capabilities.toLowerCase();
        Logs.d(TAG, "cap:" + cap);

        String password = wifiPassword;//Constant.WIFI_PASSWORD;

        WifiConfiguration config = new WifiConfiguration();
        config.SSID = "\"" + targetResult.SSID + "\"";

        // 加密方式
        if (cap.contains("wpa")) {
            config.preSharedKey = "\"" + password + "\""; // 密码
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        } else if (cap.contains("wep")) {
            int i = password.length();
            if (((i == 10 || i == 26 || i == 58)) && password.matches("[0-9A-Fa-f]*")) {
                config.wepKeys[0] = password;
            } else {
                config.wepKeys[0] = "\"" + password + "\"";
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }

        int netId = wifiManager.addNetwork(config);
        connected = wifiManager.enableNetwork(netId, true);
        Logs.d(TAG, "wifi connected:" + connected + ", netId:" + netId);
    }

2.断开连接

public void closeWifi() {
    boolean closed = wifiManager.disconnect();
    Logs.d(TAG, "wifi closed:" + closed);
}
上一篇下一篇

猜你喜欢

热点阅读