Android扫码连接WIFI实现

0,目标

APP中实现扫WIFI分享码自动连接WIFI功能

1,前提条件

设备需要有个扫码器(摄像头拍照识别也行),APP调用扫码器读取WIFI连接分享码。

2,增加权限

在AndroidManifest.xml中增加权限

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
3,参数检查

扫码成功后,对内容进行一个基本的判断,确认扫码数据中有P和T的参数

//WIFI连接
if (strResult.contains("P:") && strResult.contains("T:")) {// 自动连接wifi
   ConnectWifi(strResult);
}
4,WIFI连接调用
    private void ConnectWifi(String strResult)
    {
        //取连接参数
        String passwordTemp = strResult.substring(strResult
                .indexOf("P:"));
        password = passwordTemp.substring(2,
                passwordTemp.indexOf(";"));
        String netWorkTypeTemp = strResult.substring(strResult
                .indexOf("T:"));
        netWorkType = netWorkTypeTemp.substring(2,
                netWorkTypeTemp.indexOf(";"));
        String netWorkNameTemp = strResult.substring(strResult
                .indexOf("S:"));
        netWorkName = netWorkNameTemp.substring(2,
                netWorkNameTemp.indexOf(";"));

        WifiAdmin wifiAdmin = new WifiAdmin(MainActivity.this);
        if (!wifiAdmin.mWifiManager.isWifiEnabled()) {
            Toast.makeText(this, "开启wifi设置", Toast.LENGTH_LONG).show();
            wifiAdmin.openWifi();
        }

        int net_type = 0x13;
        if (netWorkType.compareToIgnoreCase("wpa") == 0) {
            net_type = WifiAdmin.TYPE_WPA;// wpa
        } else if (netWorkType.compareToIgnoreCase("wep") == 0) {
            net_type = WifiAdmin.TYPE_WEP;// wep
        } else {
            net_type = WifiAdmin.TYPE_NO_PASSWD;// 无加密
        }

        boolean bConnect =  wifiAdmin.addNetwork(netWorkName,password,net_type);//连接
        if(bConnect)
        {
           Toast.makeText(this, "网络连接成功", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(this, "网络连接失败", Toast.LENGTH_LONG).show();
        }

    }

5,WIFI连接类

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.util.List;

/**
 * Created by cmos.
 */
public  class WifiAdmin {
    private static String TAG="WifiManger";
    public static final int TYPE_NO_PASSWD = 0x11;
    public static final int TYPE_WEP = 0x12;
    public static final int TYPE_WPA = 0x13;
    public WifiManager mWifiManager;
    private WifiInfo mWifiInfo;
    public WifiAdmin(Context context){
        mWifiManager=  (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 添加一个网络并连接
    public boolean addNetwork(WifiConfiguration wifi){
        int netId=mWifiManager.addNetwork(wifi);
        return mWifiManager.enableNetwork(netId,true);
    }
    public boolean addNetwork(String ssid, String passwd, int type) {
        if (ssid == null || passwd == null || ssid.equals("")) {
            Log.e(TAG, "addNetwork() ## nullpointer error!");
            return false ;
        }

        if (type != TYPE_NO_PASSWD && type != TYPE_WEP && type != TYPE_WPA) {
            Log.e(TAG, "addNetwork() ## unknown type = " + type);
        }

        return addNetwork(createWifiInfo(ssid, passwd, type));
    }

    public WifiConfiguration createWifiInfo(String SSID, String password, int type) {

        Log.e(TAG, "SSID = " + SSID + "## Password = " + password + "## Type = " + type);

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";


        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            //如果已存在该SSID的wifi
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        // 分为三种情况:1没有密码2用wep加密3用wpa加密
        if (type == TYPE_NO_PASSWD) {// 没有密码
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;

        } else if (type == TYPE_WEP) {  //  wep加密
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + password + "\"";
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == TYPE_WPA) {   // 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;
    }

    //检测该SSID是否已存在
    private WifiConfiguration IsExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    // 打开WIFI
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    // 关闭WIFI
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
}
相关推荐
学不会•1 小时前
css数据不固定情况下,循环加不同背景颜色
前端·javascript·html
活宝小娜4 小时前
vue不刷新浏览器更新页面的方法
前端·javascript·vue.js
程序视点4 小时前
【Vue3新工具】Pinia.js:提升开发效率,更轻量、更高效的状态管理方案!
前端·javascript·vue.js·typescript·vue·ecmascript
coldriversnow4 小时前
在Vue中,vue document.onkeydown 无效
前端·javascript·vue.js
我开心就好o4 小时前
uniapp点左上角返回键, 重复来回跳转的问题 解决方案
前端·javascript·uni-app
开心工作室_kaic5 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
刚刚好ā5 小时前
js作用域超全介绍--全局作用域、局部作用、块级作用域
前端·javascript·vue.js·vue
沉默璇年6 小时前
react中useMemo的使用场景
前端·react.js·前端框架
yqcoder6 小时前
reactflow 中 useNodesState 模块作用
开发语言·前端·javascript
2401_882727576 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架