1 Star 0 Fork 0

ScenarioSamples/NetworkAwareness

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

网络状态监听与感知示例

介绍

本示例提供了通过 Network Kit 获取并监听网络状态的能力,可以在网络变化时执行应用预设的逻辑。

效果预览

约束与限制

  1. 本示例支持 API Version 12 Release 及以上版本。
  2. 本示例支持 HarmonyOS 5.0.0 Release SDK 及以上版本。
  3. 本示例需要使用 DevEco Studio 5.0.0 Release 及以上版本进行编译运行。

使用说明

点击 “订阅网络事件” 按钮,监听到有可用网络时,将相关信息输出在下方。

点击 “查看网络状态” 按钮,会获取当前网络信息,并输出在下方。

权限说明

需要在模块 module.json5 中声明以下权限。

  • ohos.permission.GET_NETWORK_INFO
  • ohos.permission.INTERNET

实现思路

网络事件监听

先通过 netConnection.register() 注册事件监听。之后再通过 netConnection.on() 注册相应事件的回调。

registerNetworkEvent(): void {
  this.netConnection.register((error: BusinessError) => {
    if (error) {
      this.eventOutput = `netConnection register error: ${JSON.stringify(error)}`;
      hilog.error(0x00FF, 'NetworkAwareness', this.eventOutput);
    }
  });

  // 网络可用
  this.netConnection.on('netAvailable', (data: connection.NetHandle) => {
    this.eventOutput = `network available: ${JSON.stringify(data)}`;
    hilog.info(0x00FF, 'NetworkAwareness', this.eventOutput);
    if (this.lastAvailableNetworkId === COMMON_INVALID_VAL) {
      this.lastAvailableNetworkId = data.netId;
    } else if (this.lastAvailableNetworkId === data.netId) {
      // 当前网络和上次连接的可用网络为同一网络
    } else {
      // 当前网络和上次连接的可用网络为不同网络
    }
  });

  // 网络丢失 (例如网络断开)
  this.netConnection.on('netLost', (data: connection.NetHandle) => {
    this.eventOutput = `network lost: ${JSON.stringify(data)}`;
    hilog.info(0x00FF, 'NetworkAwareness', this.eventOutput);
  });

  // 网络不可用 (例如 WIFI 图标上有感叹号)
  this.netConnection.on('netUnavailable', () => {
    this.eventOutput = `network unavailable, id is ${this.lastAvailableNetworkId}`;
    hilog.info(0x00FF, 'NetworkAwareness', this.eventOutput);
  });
}

网络状态获取

先通过 connection.getDefaultNet() 获取 netHandle。再通过 connection.getNetCapabilities() 获取 netHandle 对应的网络的能力信息。

getNetworkStatus(): void {
  connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
    if (netHandle.netId === 0) {
      // 当前没有已连接的网络时,获取的 netHandler 的 netid 为 0
      this.statusOutput = `No network connected`;
      hilog.info(0x00FF, 'NetworkAwareness', this.statusOutput);
      return;
    }
    connection.getNetCapabilities(netHandle, (error: BusinessError, netCapabilities: connection.NetCapabilities) => {
      if (error) {
        this.statusOutput = `Failed to get net capabilities. Code:${error.code}, message:${error.message}`;
        hilog.error(0x00FF, 'NetworkAwareness', this.statusOutput);
        return;
      }

      let currentNetInfoTmp =
        `上/下行带宽:${netCapabilities.linkUpBandwidthKbps}/${netCapabilities.linkDownBandwidthKbps} kb/s\n`;

      let netBearType: connection.NetBearType = netCapabilities.bearerTypes[0];
      currentNetInfoTmp += `网络类型:${getNetBearType(netBearType)}\n`;

      let properties: connection.ConnectionProperties = connection.getConnectionPropertiesSync(netHandle);
      currentNetInfoTmp += `网卡名称:${properties.interfaceName}\n`;
      currentNetInfoTmp += `所属域:${properties.domains}\n`;
      currentNetInfoTmp += `最大传输单元:${properties.mtu}\n`;

      this.statusOutput = currentNetInfoTmp;
    });
  }).catch((error: BusinessError) => {
    this.statusOutput = `netHandle get error: ${JSON.stringify(error)}`;
    hilog.error(0x00FF, 'NetworkAwareness', this.statusOutput);
  });
}

工程目录

entry/src/main/ets/
|---entryability
|---pages
    |---Index.ets                 // 示例展示页面
|---utils
    |---NetworkUtil.ets           // 网络处理类

依赖模块

参考文档

网络连接管理

ChangeLog

修改内容 时间
第一次提交 2025.03.10

空文件

简介

【鸿蒙 Harmony Next 示例 代码】本示例提供了通过 Network Kit 获取并监听网络状态的能力,可以在网络变化时执行应用预设的逻辑。 展开 收起
TypeScript
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/scenario-samples/network-awareness.git
git@gitee.com:scenario-samples/network-awareness.git
scenario-samples
network-awareness
NetworkAwareness
master

搜索帮助