一.前言

最近需要在uniapp上实现WiFi功能,将个人的研究结果记录如下(都只支持安卓APP)

  1. 使用 uni-WIFI
  2. 使用h5+ api

二.使用 uni-WIFI

完整代码地址暂未上传

如果遇到打包错误可尝试修改
在这里插入图片描述
在这里插入图片描述
将 minSdkVersion 改为21

如果是自定义基座,需要具备下面的权限

"<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_FINE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>"
  1. 判断是否有定位权限(因为使用WiFi模块需要使用定位,如果定位没有打开初始化WiFi就会失败)
    async isPermission() {
      const res = await requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
      // 当res为1表示有这个权限
      if (res === 1) {
      	// 调用WiFi初始化
      	this.wifiInit()
      } else {
        //没有权限执行的
        ...
      }
    }

权限查询的函数,基于 https://ext.dcloud.net.cn/plugin?id=594

/**
 * Android权限查询
 * @param permissionID
 * android.permission.ACCESS_FINE_LOCATION    位置权限
 * android.permission.ACCESS_COARSE_LOCATION    模糊位置权限(蓝牙\ble依赖)
 * android.permission.CAMERA    摄像头权限
 * android.permission.READ_EXTERNAL_STORAGE    外部存储(含相册)读取权限
 * android.permission.WRITE_EXTERNAL_STORAGE    外部存储(含相册)写入权限
 * android.permission.RECORD_AUDIO    麦克风权限
 * android.permission.READ_CONTACTS    通讯录读取权限
 * android.permission.WRITE_CONTACTS    通讯录写入权限
 * android.permission.READ_CALENDAR    日历读取权限
 * android.permission.WRITE_CALENDAR    日历写入权限
 * android.permission.READ_SMS    短信读取权限
 * android.permission.SEND_SMS    短信发送权限
 * android.permission.RECEIVE_SMS    接收新短信权限
 * android.permission.READ_PHONE_STATE    获取手机识别码等信息的权限
 * android.permission.CALL_PHONE    拨打电话权限
 * android.permission.READ_CALL_LOG    获取通话记录权限
 * @return {Promise<unknown>}
 */
export function requestAndroidPermission(permissionID) {
    return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
            [permissionID], // 理论上支持多个权限同时查询,但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
            function (resultObj) {
                let result = 0;
                for (let i = 0; i < resultObj.granted.length; i++) {
                    const grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限:' + grantedPermission);
                    result = 1
                }
                for (let i = 0; i < resultObj.deniedPresent.length; i++) {
                    const deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限:' + deniedPresentPermission);
                    result = 0
                }
                for (let i = 0; i < resultObj.deniedAlways.length; i++) {
                    const deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
                    result = -1
                }
                resolve(result);
                // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
                // if (result != 1) {
                // gotoAppPermissionSetting()
                // }
            },
            function (error) {
                console.log('申请权限错误:' + error.code + " = " + error.message);
                resolve({
                    code: error.code,
                    message: error.message
                });
            }
        );
    });
}

/**
 * 跳转到设置权限页面
 */
export function gotoAppPermissionSetting() {
    const Intent = plus.android.importClass("android.content.Intent");
    const Settings = plus.android.importClass("android.provider.Settings");
    const Uri = plus.android.importClass("android.net.Uri");
    const mainActivity = plus.android.runtimeMainActivity();
    const intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
    intent.setData(uri);
    mainActivity.startActivity(intent);
}

2.如果有权限开始初始化WiFi

 // 初始化
    wifiInit() {
      // #ifdef APP-PLUS
      uni.startWifi({
        fail: (e) => {
          console.log(e)
        }
      })
       // 监听获取到wifi列表
      uni.onGetWifiList(this.onGetWifiListFun)
      // 获取WiFi列表
      this.getWifiConnectInfo()
      // #endif
    }

3.获取当前连接的WiFi信息

    getWifiConnectInfo() {
      // #ifdef APP-PLUS
      uni.getConnectedWifi({
        partialInfo: true,
        success: ({wifi}) => {
          console.log(wifi)
          this.connectWifi = wifi.SSID
          return wifi
        },
        complete: () => {
          //获取WiFi列表
          this.getWifiListFun()
        }
      })
      // #endif
    }

4.获取wifi列表

 getWifiListFun() {
      // #ifdef APP-PLUS
      uni.getWifiList({
        complete: () => {
          // 移除监听函数
          uni.offGetWifiList(this.onGetWifiListFun)
          // 获取当前连接的WiFi信息
        }
      })
      // #endif
    }

监听获取到的WiFi列表函数

    onGetWifiListFun(info) {
      this.wifiList = []
      let wifiList = []
      // 过滤掉没有SSID的 还有我个人对信号的处理,用来渲染对应的样式的
        wifiList = info.wifiList.filter(item => {
        if (item.signalStrength >= -55) {
          item['signalDefine'] = [true, true, true]
        } else if (item.signalStrength >= -66) {
          item['signalDefine'] = [false, true, true]
        } else if (item.signalStrength >= -88) {
          item['signalDefine'] = [false, false, true]
        } else if (item.signalStrength >= -100) {
          item['signalDefine'] = [false, false, false]
        }
        return item.SSID
      })
      // 按信号强度排序
      wifiList = wifiList.sort((a, b) => {
        return b.signalStrength - a.signalStrength
      })
      // 取当前连接的WiFi的信号
      const connectResIndex = wifiList.findIndex(item => item.SSID === this.connectWifi)
      const connectRes = wifiList[connectResIndex]
      if (connectRes) {
        this.connectWifiSignal = connectRes['signalDefine']
        this.connectRes = connectRes
      }
      wifiList.splice(connectResIndex, 1)
      this.wifiList = wifiList
      // 获取成功,关闭loading
      uni.hideLoading();
      console.log('wifiList', wifiList)
      console.log('wifiList', this.wifiList)
      // console.log(info)
    },

5.连接WiFi

 uni.connectWifi({
        SSID: wifiInfo.SSID,
        BSSID: wifiInfo.BSSID,
        //WiFi的密码 
        password: this.pwd,
        partialInfo: true,
        maunal: false,
        fail: (e) => {
          console.log(e)
          let msg
          switch (e.errCode) {
            case 12002: {
              msg = 'WI-FI密码错误!'
              break
            }
            case 12013: {
              msg = 'Wi-Fi 配置过期,建议忘记 Wi-Fi 后重试!'
              break
            }
            case 12005: {
              msg = '未打开 Wi-Fi!'
              break
            }
            default: {
              msg = e.errMsg
            }
          }
          uni.showToast({
            icon: 'none',
            title: msg
          })
        },
        success: (info) => {
          if (info.errCode === 0) {
            uni.showToast({
              icon: 'none',
              title: `${info.wifi.SSID}连接成功!`
            })
            //连接成功后的处理
            ...
          }
        }
      })

三.使用h5+ api

这里没有实现监听到WiFi是否连接成功,但我找了下网上资料,可以监听广播的方式,我试了几种没有找到合适的,希望大家能补充下.


<template>
  <view>
    <button @click="getWifiList">扫描WiFi</button>
    <view>
      <view class="wifi-item" @click="connectNew(item.name,'secnet-cd',item.bssid,item.sindex)"
            v-for="(item,index) in wifiArray"
            :key="index">
        {{ item.name }}
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      wifiManager: null,
      WifiConfiguration: null,
      wifis: null,
      nowWifiInfo: null,
      wifiArray: [],
      ArrayList: null
    };
  },
  // #ifdef APP-PLUS
  methods: {
    // 初始化WiFi
    initWifi() {
      const MainActivity = plus.android.runtimeMainActivity()
      const Context = plus.android.importClass("android.content.Context");
      plus.android.importClass("android.net.wifi.WifiManager");
      plus.android.importClass("java.util.List");
      this.ArrayList = plus.android.importClass("java.util.ArrayList");
      plus.android.importClass("android.net.wifi.ScanResult");
      plus.android.importClass("android.net.wifi.WifiInfo");
      plus.android.importClass("java.util.BitSet");
      this.WifiConfiguration = plus.android.importClass("android.net.wifi.WifiConfiguration");
      this.wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)
      console.log('wifi初始化成功')

      //引入过滤器
      //const IntentFilter = plus.android.importClass('android.content.IntentFilter');
      //const Intent = plus.android.importClass('android.content.Intent');
      // 注册广播
      //let receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
      //   onReceive: function (context, intent) {
      //    console.log('*********************************************************');
      //     console.log(intent.getAction());
      //      console.log(context.toString())
      //      console.log(intent.toString())
      //    console.log('*********************************************************');
      // } //实现onReceiver回调函数
      //});
      //let filter = new IntentFilter();
      // filter.addAction('android.net.wifi.STATE_CHANGE');
      // filter.addAction('android.net.wifi.WIFI_STATE_CHANGED');
      // filter.addAction('android.net.wifi.LINK_CONFIGURATION_CHANGED');
      // filter.addAction('android.permission.ACCESS_WIFI_STATE');
      // filter.addAction('android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION');
      //filter.addAction('android.net.wifi.STATE_CHANGE');
      //MainActivity.registerReceiver(receiver, filter); //监听广播

      this.androidOpenWifi()
    },
    // getReceive(context,intent){
    //   console.log(context,intent)
    // },
    // 打开安卓的wifi
    androidOpenWifi() {
      let bRet = false;
      const wifiManager = this.wifiManager
      if (!wifiManager.isWifiEnabled()) {
        bRet = wifiManager.setWifiEnabled(true); //返回自动打开的结果
        console.log("打开wifi的返回结果是" + bRet)
      } else {
        bRet = true;
        console.log("wifi原本已经打开")
      }
      return bRet;
    },
    // 获取WiFi列表
    getWifiList() {
      const resultList = this.wifiManager.getScanResults()
      this.wifis = resultList
      const len = resultList.size()
      let wifiArray = []
      for (let i = 0; i < len; i++) {
        // console.log(resultList.get(i).toString())
        const oneWiFi = {
          sindex: i,
          name: resultList.get(i).plusGetAttribute('SSID'),
          bssid: resultList.get(i).plusGetAttribute('BSSID'),
          signal: resultList.get(i).plusGetAttribute('level')
        }
        wifiArray.push(oneWiFi);
      }
      this.wifiArray = wifiArray
      console.log(wifiArray)
      this.getNowWifi()
    },
    // 获取当前连接的wifi
    getNowWifi() {
      const info = this.wifiManager.getConnectionInfo();
      console.log(info.toString())
      let ssid = info.getSSID()
      let rssi = info.getRssi()
      console.log(rssi)
      ssid = ssid.replace(/(^\"*)|(\"*$)/g, "")
      console.log(ssid)
    },
    // 连接新的WiFi
    connectNew(ssid, pwd, BSSID, index) {
      // uni.onNetworkStatusChange(function (res) {
      //   console.log(res.isConnected);
      //   console.log(res.networkType);
      // });
      console.log({ssid, pwd})
      const wifiManager = this.wifiManager
      var wifiConfig = this.androidCreateWifiInfo(ssid, pwd, 'wpa', BSSID);
      if (wifiConfig == null) {
        console.log("wifiConfig is null!")
        return;
      }
      //WifiConfiguration
      const tempConfig = this.isExsitsAndroid(ssid)
      if (tempConfig != null) {
        // console.log("删除原来连接的wifi" + tempConfig);
        wifiManager.removeNetwork(tempConfig.plusGetAttribute('networkId'));
      }
      // console.log("要连接的新的wifi配置:" + wifiConfig)
      // console.log("要连接的新的wifi配置:", wifiConfig)
      const netID = wifiManager.addNetwork(wifiConfig);
      // console.log(netID);
      //boolean
      const enabled = wifiManager.enableNetwork(netID, true);
      console.log("enableNetwork status enable=" + enabled)
      // boolean
      const connected = wifiManager.reconnect();
      console.log("enableNetwork connected=" + connected)


      // const timer = setInterval(() => {
      //   const wifiState = wifiManager.getWifiState()
      //   const wifiStateNetworks = wifiManager.getConfiguredNetworks()
      //   console.log(wifiState)
      //   console.log(wifiStateNetworks.toString())
      // }, 500)
      // setTimeout(()=>{
      //   clearInterval(timer)
      // },10000)
      // const existingConfigs = wifiManager.getConfiguredNetworks()
      // console.log(existingConfigs)
      // wifiManager.enableNetwork(this.wifis.get(index).plusGetAttribute('networkId'), true);
      // setTimeout(()=>{
      //   this.getNowWifi()
      // },3000)
    },
    // 创建新的WiFi信息
    androidCreateWifiInfo(SSID, Password, Type, BSSID) {
      console.log(SSID, Password, Type)
      const WifiConfiguration = this.WifiConfiguration;
      let config = new WifiConfiguration();
      config.plusGetAttribute('allowedAuthAlgorithms').clear();
      config.plusGetAttribute('allowedGroupCiphers').clear();
      config.plusGetAttribute('allowedKeyManagement').clear();
      config.plusGetAttribute('allowedPairwiseCiphers').clear();
      config.plusGetAttribute('allowedProtocols').clear();
      config.plusSetAttribute('SSID', '"' + SSID + '"');
      // config.plusSetAttribute('BSSID', '"' + BSSID + '"');
      // nopass
      if (Type === "nopass") {
        config.plusSetAttribute('preSharedKey', "");
        config.plusGetAttribute('allowedKeyManagement').set(WifiConfiguration.KeyMgmt.NONE);
        config.plusSetAttribute('wepTxKeyIndex', 0);
      }
      // wep
      if (Type === "wep") {
        if (!Password !== "") {
          if (isHexWepKey(Password)) {
            config.plusSetAttribute('preSharedKey', Password);
          } else {
            config.plusSetAttribute('preSharedKey', "\"" + Password + "\"");
          }
        }
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
        config.allowedKeyManagement.set(KeyMgmt.NONE);
        config.plusSetAttribute('wepTxKeyIndex', 0);
      }
      // wpa
      if (Type === "wpa") {
        // config.plusSetAttribute('preSharedKey', "\"" + Password + "\"");
        config.plusSetAttribute('preSharedKey', '"' + Password + '"');
        config.plusSetAttribute('hiddenSSID', true);
        config.plusGetAttribute('allowedAuthAlgorithms').set(WifiConfiguration.AuthAlgorithm.OPEN);
        config.plusGetAttribute('allowedGroupCiphers').set(WifiConfiguration.GroupCipher.TKIP);
        config.plusGetAttribute('allowedKeyManagement').set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.plusGetAttribute('allowedPairwiseCiphers').set(WifiConfiguration.PairwiseCipher.TKIP);
        // 此处需要修改否则不能自动重联
        //config.plusGetAttribute('allowedProtocols').set(WifiConfiguration.Protocol.WPA);
        config.plusGetAttribute('allowedGroupCiphers').set(WifiConfiguration.GroupCipher.CCMP);
        config.plusGetAttribute('allowedPairwiseCiphers').set(WifiConfiguration.PairwiseCipher.CCMP);
        config.plusSetAttribute('status', WifiConfiguration.Status.ENABLED);
      }
      return config;
    },
    // 查看以前是否也配置过这个网络
    isExsitsAndroid(sSID) {
      console.log("查看以前是否也配置过这个网络" + sSID);    //WifiConfiguration
      const ArrayList = this.ArrayList
      const wifiManager = this.wifiManager
      let existingConfigs = new ArrayList();
      existingConfigs = wifiManager.getConfiguredNetworks();
      if (existingConfigs.size() != 0) {
        for (var i = 0; i < existingConfigs.size(); i++) {
          if (existingConfigs.get(i).plusGetAttribute('SSID') == ("\"" + sSID + "\"")) {
            console.log("该制定的ssid存在于配置中:" + sSID);
            return existingConfigs.get(i);
          }
        }
      }
      console.log("该ssid没有配置过")
      return null;
    }
  },
  onLoad() {
    this.initWifi()
  }
  //  #endif
}
</script>

<style>
.wifi-item {
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #eee;
}
</style>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐