HarmonyOS wifi连接demo?

如题:HarmonyOS wifi连接demo?

阅读 530
1 个回答

参考示例:

utils/PermissionsUtil:

import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

/**
 * 权限管理工具类
 * 能力:检查权限是否已存在、请求用户授权
 */
class PermissionsUtil {

  /**
   * 校验应用是否被授予定位权限
   * @param permissions
   * @returns
   */
  async checkPermissions(permissions: Array<Permissions>): Promise<void> {
    let applyResult: boolean = false;
    for (let permission of permissions) {
      let grantStatus: abilityAccessCtrl.GrantStatus = await this.checkAccessToken(permission);
      if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        applyResult = true;
      } else {
        applyResult = false;
      }
    }
    if (!applyResult) {
      this.requestPermissions(permissions);
    }
  }

  async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
    // 获取应用程序的accessTokenID
    let tokenId: number = 0;
    try {
      let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
    }

    // 校验应用是否被授予权限
    try {
      grantStatus = await atManager.checkAccessToken(tokenId, permission);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`);
    }

    return grantStatus;
  }

  /**
   * 申请用户授权
   * @param permissions
   */
  requestPermissions(permissions: Array<Permissions>): void {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext, permissions)
      .then((data: PermissionRequestResult) => {
        console.info('request Permissions success')
      })
      .catch((err: BusinessError) => {
        console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
      })
  }
}

export default new PermissionsUtil();

pages/Index:

import Logger from '../model/Logger'
import { WifiModel, WifiType } from '../model/WifiModel'
import { router } from '@kit.ArkUI';
import { Permissions } from '@kit.AbilityKit';
import { wifiManager } from '@kit.ConnectivityKit';
import { AvailableWifi } from '../component/AvailableWifi'
import PermissionsUtil from '../utils/PermissionsUtil'

@Entry
@Component
struct Index {
  private wifiModel: WifiModel = new WifiModel()
  @State message: string = 'Hello World';
  @State isSwitchOn: boolean = false;
  private permissions: Array<Permissions> = ['ohos.permission.SET_WIFI_INFO', 'ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];
  @State isLinked: boolean = false
  @State linkedInfo: wifiManager.WifiLinkedInfo | undefined = undefined
  @State p2pLinkedInfo: wifiManager.WifiP2pLinkedInfo | undefined = undefined
  @State networkId: number = 0;

  // 扫描wifi
  async scan() {
    // 获取有关Wi-Fi连接的信息,存入linkedInfo
    await this.getLinkedInfo()
    // 不停地扫描wifi
    let result: Array<WifiType> = await this.wifiModel.getScanInfos()
    if (this.isSwitchOn) {
      AppStorage.setOrCreate('wifiList', result)
      setTimeout(async () => {
        await this.scan()
      }, 3000)
    }
  }

  // 获取有关Wi-Fi连接的信息,存入linkedInfo
  async getLinkedInfo() {
    try {
      let wifiLinkedInfo = await wifiManager.getLinkedInfo()
      let wifiP2pLinkedInfo = await wifiManager.getP2pLinkedInfo()
      console.log('wifiLinkedInfo111:'+JSON.stringify(wifiLinkedInfo))
      console.log('p2pLinked111:'+JSON.stringify(wifiP2pLinkedInfo))
      if (wifiLinkedInfo === null || wifiLinkedInfo.bssid === '') {
        this.isLinked = false
        this.linkedInfo = undefined
        return
      }
      this.isLinked = true
      this.linkedInfo = wifiLinkedInfo
      this.p2pLinkedInfo = wifiP2pLinkedInfo
    } catch (err) {
      Logger.info(`getLinkedInfo failed err is ${JSON.stringify(err)}`)
    }
  }

  // 获取当前组信息,需要一直处于连接状态才行
  getCurrentGroup() {
    wifiManager.getCurrentGroup().then((data:wifiManager.WifiP2pGroupInfo) => {
      Logger.info(`getCurrentGroup is ${JSON.stringify(data)}`)
    })
  }

  // 监听wifi的变化
  addListener() {
    // 连接状态改变时,修改连接信息
    wifiManager.on('wifiConnectionChange', async state => {
      Logger.log(`wifiConnectionChange: ${state}`)
      await this.getLinkedInfo()
    })
    // wifi状态改变时,先清空wifi列表,然后判断是否是开启状态,如果是就扫描
    wifiManager.on('wifiStateChange', state => {
      Logger.log(`wifiStateLisener state: ${state}`)
      AppStorage.setOrCreate('wifiList', [])
      if (state === 1) { // 1: wifi is enable, 0:wifi is disable
        this.scan()
      }
    })
  }

  async aboutToAppear() {
    await PermissionsUtil.checkPermissions(this.permissions)
    setTimeout(() => {
      // 如果wifi是开的,就记录下状态,然后扫描wifi,并获取连接信息
      if (wifiManager.isWifiActive()) {
        Logger.log('wifi is active')
        this.isSwitchOn = true
        // wifiManager.scan()
        this.scan()
        this.getLinkedInfo()
      }
      // 启动监听
      this.addListener()
      this.getCurrentGroup()
    }, 2000)
  }

  build() {
    Column() {
      Row() {
        Text('eTSWLAN')
          .fontColor(Color.White)
          .fontSize(25)
          .layoutWeight(1)
        Button() {
          Text('详情')
        }
        .id('about')
        .type(ButtonType.Normal)
        .height('90%')
        .backgroundColor('#0D9FFB')
        .onClick(() => {
          router.pushUrl({ url: 'pages/About' })
        })
      }
      .width('100%')
      .height('8%')
      .constraintSize({ minHeight: 50 })
      .padding({ left: 15 })
      .backgroundColor('#0D9FFB')
      Row(){
        Text('wlan')
          .fontSize(22)
          .fontWeight(FontWeight.Bold)
          .height(40)
        Column() {
          Toggle({ type: ToggleType.Switch, isOn: this.isSwitchOn })
            .id('switch')
        }
      }
      .width('100%')
      .padding({ left: 16, right: 16 })
      if (this.isLinked && this.isSwitchOn) {
        Column() {
          Text('connected')
            .fontSize(22)
            .width('100%')
          Row() {
            Text(this.linkedInfo?.ssid)
              .fontSize(20)
              .fontColor(Color.Black)
              .layoutWeight(1)
            Text(this.linkedInfo?.band===1?'2.4GHZ':'5GHZ')
              .fontSize(18)
              .fontColor(Color.Black)
          }
          .width('100%')
          .padding(10)
          .margin({ left: 16, right: 16 })
          .border({ radius: 15, color: Color.Gray, width: 1 })
          .backgroundColor(Color.White)
        }
        .width('100%')
        .padding({ left: 16, right: 16 })
      }
      if (this.isSwitchOn) {
        AvailableWifi({ linkedInfo: this.linkedInfo })
      }
    }
  }
  aboutToDisappear() {
    wifiManager.off('wifiConnectionChange')
    wifiManager.off('wifiStateChange')
  }
}

page/About:

import router from '@ohos.router'
import { WifiModel } from '../model/WifiModel'
import { InfoView } from '../component/InfoView'

@Entry
@Component
struct About {
  private wifiModel: WifiModel = new WifiModel()
  aboutToAppear(): void {
    this.wifiModel = new WifiModel()
  }

  build() {
    Column() {
      Row() {
        Image($r('app.media.ic_back'))
          .size({ width: 50, height: '100%' })
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.back()
          })
          .id('back')

        Text('about')
          .fontColor(Color.White)
          .fontSize(25)
          .layoutWeight(1)
      }
      .width('100%')
      .height('8%')
      .constraintSize({ minHeight: 50 })
      .backgroundColor('#0D9FFB')

      Scroll() {
        Column() {
          InfoView({ infoList: this.wifiModel.getIpInfo() })
          InfoView({ infoList: this.wifiModel.getCountryCode() })
          InfoView({ infoList: this.wifiModel.getFeatureSupport() })
        }
      }
      .layoutWeight(1)
    }
  }
}

component/AvailableWifi:

import Logger from '../model/Logger'
import prompt from '@ohos.promptAction'
import { WifiView } from '../component/WifiView'
import WifiDataSource from '../component/BasicDataSource'
import wifi from '@ohos.wifiManager'
import { common, Want } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'

@Component
export struct AvailableWifi {
  private linkedInfo: wifi.WifiLinkedInfo | undefined;
  @StorageLink('wifiList') @Watch('wifiListRefresh') wifiList: Array<wifi.WifiScanInfo> = []
  @State wifiDataResource: WifiDataSource = new WifiDataSource(this.wifiList)
  @State scanInfo: wifi.WifiScanInfo | undefined = undefined
  @State networkId: number = 0;

  build() {
    List() {
      ListItem() {
        Row() {
          Text('available_wlan')
            .fontSize(22)
            .layoutWeight(1)
        }
        .id('validWlan')
        .width('100%')
      }

      LazyForEach(this.wifiDataResource, (item:wifi.WifiScanInfo, index) => {
        ListItem() {
          WifiView({ wifi: item })
        }
        .id(`Wifi${index}`)
        .onClick(() => {
          Logger.info('wifi click')
          this.scanInfo = item
          if (this.linkedInfo !== null && item.ssid === this.linkedInfo?.ssid) {
            prompt.showToast({ message: 'this wifi is connected' })
            return
          }
          let context = getContext(this) as common.UIAbilityContext;
          let want:Want = {
            bundleName: 'com.huawei.hmos.settings',
            abilityName: 'com.huawei.hmos.settings.MainAbility',
            uri: 'wifi_entry'
          };
          context.startAbility(want,(err: BusinessError)=>{
            if (err.code) {
              // 处理业务逻辑错误
              console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
              return;
            }
          })
        })
      }, (item:wifi.WifiScanInfo) => JSON.stringify(item))
    }
    .width('100%')
    .height('100%')
    .padding({ left: 16, right: 16 })
    .layoutWeight(1)
    .divider({ strokeWidth: 1, color: Color.Gray, startMargin: 10, endMargin: 10 })
    .margin({ top: 10 })
  }

  wifiListRefresh() {
    this.wifiDataResource.pushArrayData(this.wifiList)
    this.wifiDataResource.notifyDataReload()
  }
}

component/BasicDataSource:

import wifi from '@ohos.wifiManager'
import Logger from '../model/Logger'

export default class WifiDataSource {
  private listeners: DataChangeListener[] = []
  private dataArray: wifi.WifiScanInfo[] = []

  constructor(data: wifi.WifiScanInfo[]) {
    this.dataArray = data
  }

  public totalCount(): number {
    return this.dataArray.length
  }

  public getData(index: number): wifi.WifiScanInfo {
    return this.dataArray[index]
  }

  public addData(index: number, data: wifi.WifiScanInfo): void {
    this.dataArray.splice(index, 0, data)
    this.notifyDataAdd(index)
  }

  public pushData(data: wifi.WifiScanInfo): void {
    this.dataArray.push(data)
    this.notifyDataAdd(this.dataArray.length - 1)
  }

  public pushArrayData(data: wifi.WifiScanInfo[]): void {
    this.dataArray = data;
    this.notifyDataAdd(this.dataArray.length - 1);
  }

  registerDataChangeListener(listener: DataChangeListener): void {
    if (this.listeners.indexOf(listener) < 0) {
      Logger.info('add listener')
      this.listeners.push(listener)
    }
  }

  unregisterDataChangeListener(listener: DataChangeListener): void {
    const POS = this.listeners.indexOf(listener)
    if (POS >= 0) {
      Logger.info('remove listener')
      this.listeners.splice(POS, 1)
    }
  }

  notifyDataReload(): void {
    this.listeners.forEach(listener => {
      listener.onDataReloaded()
    })
  }

  notifyDataAdd(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataAdd(index)
    })
  }

  notifyDataChange(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataChange(index)
    })
  }

  notifyDataDelete(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataDelete(index)
    })
  }

  notifyDataMove(from: number, to: number): void {
    this.listeners.forEach(listener => {
      listener.onDataMove(from, to)
    })
  }
}

component/WifiView:

import Logger from '../model/Logger'
import wifi from '@ohos.wifiManager'
@Component
export struct WifiView {
  private wifi: wifi.WifiScanInfo | undefined = undefined
  private securityString: string = 'encryption'
  @State isLock: boolean = true
  aboutToAppear() {
    Logger.debug(`aboutToAppear ${JSON.stringify(this.wifi)}`)
    if (this.wifi && this.wifi.securityType) {
      if (this.wifi.securityType.valueOf() === 0 || this.wifi.securityType === 1) {
        this.securityString = 'open'
        this.isLock = false
      }
    }
  }

  build() {
    Row() {
      Column() {
        if (this.wifi) {
          if (this.wifi.ssid) {
            Text(this.wifi.ssid)
              .fontSize(20)
              .width('100%')
          }
        }
        Text(this.securityString)
          .fontSize(18)
          .fontColor(Color.Gray)
          .width('100%')
      }
      .layoutWeight(1)

      Stack({ alignContent: Alignment.BottomEnd }) {
        Image($r('app.media.wifi'))
          .height(30)
          .width(30)
          .objectFit(ImageFit.Contain)
        if (this.isLock) {
          Image($r('app.media.lock'))
            .objectFit(ImageFit.Contain)
            .width(15)
            .height(15)
        }
      }
      .width(40)
      .height(40)
      .margin({ right: 10 })
    }
    .backgroundColor(Color.White)
    .width('100%')
    .padding(10)
  }
}
import prompt from '@ohos.promptAction'
import wifi from '@ohos.wifiManager'
import Logger from '../model/Logger'
import ExtendObject from './ExtendObject'
export class WifiType {
  ssid: string = '';
  bssid: string = '';
  securityType: wifi.WifiSecurityType = wifi.WifiSecurityType.WIFI_SEC_TYPE_INVALID;
  rssi: number = 0;
  band: number = 0;
  frequency: number = 0;
  timestamp: number = 0;
}

export class WifiModel {
  async getScanInfos(): Promise<Array<WifiType>> {
    Logger.log('scanWifi begin')
    let wifiList: Array<WifiType> = []
    let result: Array<wifi.WifiScanInfo> = []
    try {
      result = await wifi.getScanInfoList()
    } catch (err) {
      Logger.log(`scan info err: ${JSON.stringify(err)}`)
      return wifiList
    }
    Logger.log(`scan info call back: ${result.length}`)
    for (let i = 0; i < result.length; ++i) {
      //根据格力设备前缀过滤(GR,JD-GR)
      wifiList.push({
        ssid: result[i].ssid,
        bssid: result[i].bssid,
        securityType: result[i].securityType,
        rssi: result[i].rssi,
        band: result[i].band,
        frequency: result[i].frequency,
        timestamp: result[i].timestamp
      })
    }
    return wifiList
  }

  connectNetwork(scanInfo: wifi.WifiScanInfo, psw: string) {
    prompt.showToast({ message: 'connecting', duration: 5000 })
    Logger.debug(`connectNetwork bssid=${scanInfo.bssid}`)
    // 这里因为api问题,需要声明为any,已提单
    console.log('connect11111:'+JSON.stringify(scanInfo))
    let deviceConfig: wifi.WifiDeviceConfig = {
      ssid: scanInfo.ssid,
      bssid: scanInfo.bssid,
      preSharedKey: psw,
      isHiddenSsid: false,
      securityType: scanInfo.securityType
    }
    try {
      // this.networkId=wifi.addCandidateConfig(deviceConfig)
      wifi.addCandidateConfig(deviceConfig).then(result => {
        console.info("result:" + JSON.stringify(result));
        let networkId = result;
        wifi.connectToCandidateConfig(networkId)
      }).catch((err:number) => {
        console.error("failed:" + JSON.stringify(err));
      });
    } catch (err) {
      Logger.debug(`addDeviceConfig fail err is ${JSON.stringify(err)}`)
    }
  }

  resolveIP(ip: number) {
    let address: string = ip.toString()
    console.log('adress1111:'+address)
    if (address === '0') {
      return '00:00:000:000'
    }
    address.substring(0, 2)
    return `${address.substring(0, 2)}:${address.substring(2, 4)}:${address.substring(4, 7)}:${address.substring(7, 10)}`
  }

  getIpInfo() {
    let ipInfoList: Array<ExtendObject> = []
    let ipInfo = wifi.getIpInfo()
    Logger.info(`getIpInfo=${JSON.stringify(ipInfo)}`)
    ipInfoList.push(new ExtendObject('ip_address', this.resolveIP(ipInfo.ipAddress)))
    ipInfoList.push(new ExtendObject('gate_way', this.resolveIP(ipInfo.gateway)))

    ipInfoList.push(new ExtendObject('net_mask', this.resolveIP(ipInfo.netmask)))
    ipInfoList.push(new ExtendObject('primary_dns_adress', this.resolveIP(ipInfo.primaryDns)))
    ipInfoList.push(new ExtendObject('second_dns_adress', this.resolveIP(ipInfo.secondDns)))

    ipInfoList.push(new ExtendObject('server_ip', this.resolveIP(ipInfo.serverIp)))
    ipInfoList.push(new ExtendObject('lease_duration', this.resolveIP(ipInfo.leaseDuration)))
    return ipInfoList
  }

  getCountryCode() {
    let countryCodeList: Array<ExtendObject> = []
    let countryCode = wifi.getCountryCode()
    countryCodeList.push(new ExtendObject('country_code', countryCode))
    return countryCodeList
  }

  getFeatureSupport() {
    let featureSupportedList: Array<ExtendObject> = []
    featureSupportedList.push(new ExtendObject('infrastructure_feature', wifi.isFeatureSupported(0x0001).toString()))
    featureSupportedList.push(new ExtendObject('ghz_feature', wifi.isFeatureSupported(0x0002).toString()))
    featureSupportedList.push(new ExtendObject('gas_anqp_feature', wifi.isFeatureSupported(0x0004).toString()))
    featureSupportedList.push(new ExtendObject('wifi_direct', wifi.isFeatureSupported(0x0008).toString()))
    featureSupportedList.push(new ExtendObject('soft_ap', wifi.isFeatureSupported(0x0010).toString()))
    featureSupportedList.push(new ExtendObject('wifi_aware', wifi.isFeatureSupported(0x0040).toString()))
    return featureSupportedList
  }
}

ExtendObject
export default class ExtendObject {
  public key: string = '';
  public value: string = '';
  constructor(key: string, value: string) {
    this.key = key;
    this.value = value
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏