HarmonyOS编程开发实战:网络状态监测示例

185 篇文章 0 订阅
181 篇文章 1 订阅

1. 网络状态简介

移动设备一般都具备移动网络和无线WIFI的连接能力,有些还可以接入有线以太网,这些网络可以根据需要随时切换,在网络切换过程中,伴随着网络状态的变化,比如网卡名称、IP地址、上传下载能力等等,鸿蒙提供了网络状态变化的监测api,可以随时根据需要捕获状态的改变。

2. 网络状态监测常用方法

鸿蒙封装的connection模块提供了状态监测能力,使用如下的方式导入:

import connection from '@ohos.net.connection'

connection模块包括了众多的操作方法,就本文而言,重点需要掌握的是如下八个:

1)createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection

返回一个NetConnection对象,参数netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。

2)register(callback: AsyncCallback<void>): void

订阅指定网络状态变化的通知,只有订阅后才能得到后续的回调。

3)unregister(callback: AsyncCallback<void>): void

取消订阅默认网络状态变化的通知。

4)on(type: 'netAvailable', callback: Callback<NetHandle>): void

订阅网络可用事件。

5)on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void

订阅网络能力变化事件。

6)on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void

订阅网络连接信息变化事件。

7)on(type: 'netLost', callback: Callback<NetHandle>): void

订阅网络丢失事件。

8)on(type: 'netUnavailable', callback: Callback<void>): void

订阅网络不可用事件。

3. 网络状态监测示例

本示例会获取当前设备的网络状态变化,运行后的初始界面如下所示:

cke_68441.jpeg

下面详细介绍创建该应用的步骤。

步骤1:创建Empty Ability项目。

步骤2:在module.json5配置文件加上对权限的声明:

"requestPermissions": [
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      }
    ]
这里添加了获取WIFI信息的权限。

步骤3:在Index.ets文件里添加如下的代码:

import connection from '@ohos.net.connection';

@Entry
@Component
struct Index {
  //连接、通讯历史记录
  @State msgHistory: string = ''
  @State listening: boolean = false
  currentNet: connection.NetConnection
  scroller: Scroller = new Scroller()

  build() {
    Row() {
      Column() {
        Text("网络状态监测")
          .fontSize(14)
          .fontWeight(FontWeight.Bold)
          .width('100%')
          .textAlign(TextAlign.Center)
          .padding(10)

        Flex({ justifyContent: FlexAlign.End, alignItems: ItemAlign.Center }) {

          Button(this.listening ? "停止监测" : "开始监测")
            .width(120)
            .fontSize(14)
            .flexGrow(0)
            .onClick(() => {
              this.listenButClick()
            })
        }
        .width('100%')
        .padding(10)

        Scroll(this.scroller) {
          Text(this.msgHistory)
            .textAlign(TextAlign.Start)
            .padding(10)
            .width('100%')
            .backgroundColor(0xeeeeee)
        }
        .align(Alignment.Top)
        .backgroundColor(0xeeeeee)
        .height(300)
        .flexGrow(1)
        .scrollable(ScrollDirection.Vertical)
        .scrollBar(BarState.On)
        .scrollBarWidth(20)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .height('100%')
    }
    .height('100%')
  }

  //监听按钮点击
  listenButClick() {
    this.listening = !this.listening
    if (this.listening) {

      this.currentNet = connection.createNetConnection()
      this.currentNet.register((error) => {
        if (error) {
          this.msgHistory += "订阅失败" + JSON.stringify(error) + "\r\n"
        } else {
          this.msgHistory += "订阅成功\r\n"
        }
      })

      this.currentNet.on("netAvailable", (data) => {
        this.msgHistory += "网络有效\r\n"
      })

      this.currentNet.on("netCapabilitiesChange", (data) => {
        let netType = ""
        if (data.netCap.bearerTypes[0].valueOf() == 0) {
          netType = "蜂窝网络"
        } else if (data.netCap.bearerTypes[0].valueOf() == 1) {
          netType = "Wi-Fi网络"
        }
        else if (data.netCap.bearerTypes[0].valueOf() == 3) {
          netType = "以太网网络"
        }

        this.msgHistory += `网络类型:${netType}\r\n`
        this.msgHistory += `网络能力(kbps):${data.netCap.linkUpBandwidthKbps}/${data.netCap.linkDownBandwidthKbps}\r\n`
      })

      this.currentNet.on("netConnectionPropertiesChange", (data) => {
        this.msgHistory += `网卡名称:${data.connectionProperties.interfaceName}\r\n`
        for (let i = 0; i < data.connectionProperties.dnses.length; i++) {
          this.msgHistory += `DNS${i}:${data.connectionProperties.dnses[i].address}\r\n`
        }

        for (let i = 0; i < data.connectionProperties.linkAddresses.length; i++) {
          this.msgHistory += `IP${i}:${data.connectionProperties.linkAddresses[i].address.address}\r\n`
        }

        this.msgHistory += `mtu:${data.connectionProperties.mtu}\r\n`
      })

      this.currentNet.on("netLost", (data) => {
        this.msgHistory += `网络丢失\r\n`
      })

      this.currentNet.on("netUnavailable", (data) => {
        this.msgHistory += `网络不可用\r\n`
      })
    }
    else {
      this.currentNet.unregister(() => {
      })
    }
  }
}

步骤4:编译运行,可以使用模拟器或者真机。

步骤5:单击“开始监测”按钮,然后可以通过断开和链接WLAN模拟网络状态变化,截图如下所示:

cke_81656.jpeg

这样就完成了一个简单的网络状态监测应用。

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值