HarmonyOS NEXT——【鸿蒙监听网络状态变化】

当在鸿蒙应用中,网络状态发生变化,我们需要实现监听网络状态的变化,做出相对应的提示,比如退出登录或者退出应用之类的操作。那么我们需要监听当前网络的状态,以下是我封装的代码提供参考:

效果:

参考代码:

TypeScript 复制代码
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { CommonConstants } from '../constants/CommonConstants';
import { JumpTool } from '.';
import { DialogContents, H5ShowCommonDialog } from '../../view/H5CommonDialog';
import { WindowUtils } from '../constants/WindowUtils';
import { LoginTool } from './LoginTool';
import Logger from './Logger';
​
export class ListenNetworkState {
  private static oldNetType: string | null = null
  private static newNetType: string | null = null
​
  /**
   *  获取旧网络
   * @param
   * @returns
   */
  static async getOldNet() {
    connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
      if (netHandle.netId == 0) {
        // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
        return;
      }
      connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
        if (error) {
          return;
        }
        // Logger.info("Succeeded to get data: " + JSON.stringify(data));
        if (data.bearerTypes[0] == 0) {
          ListenNetworkState.oldNetType = '蜂窝网络'
          // promptAction.showToast({ message: '蜂窝网络' })
        }
        if (data.bearerTypes[0] == 1) {
          ListenNetworkState.oldNetType = 'Wi-Fi网络'
          // promptAction.showToast({ message: 'Wi-Fi网络' })
        }
      })
    }).catch((error: BusinessError) => {
    });
  }
​
  /**
   * 监听网络是否变化
   * @param
   * @returns true 变化 false 无变化
   */
  static async listenNetwork() {
    let isNetworkChanged = false;
    await ListenNetworkState.getOldNet();
    let currentNet = connection.createNetConnection();
    currentNet.register((error) => {
      if (error) {
        // Logger.info('订阅失败' + JSON.stringify(error));
      } else {
        // Logger.info('订阅成功' + JSON.stringify(error));
      }
    });
​
    //网络切换时
    currentNet.on("netCapabilitiesChange", (data) => {
      if (data.netCap.bearerTypes[0] == 0) {
        ListenNetworkState.newNetType = '蜂窝网络';
      }
      if (data.netCap.bearerTypes[0] == 1) {
        ListenNetworkState.newNetType = 'Wi-Fi网络';
      }
      if (ListenNetworkState.oldNetType !== ListenNetworkState.newNetType) {
        if (CommonConstants.ISLOGIN) {
          LoginTool.logOut(false, false)
​
          let context: DialogContents = {
            title: "提示",
            message: '网络发生变化,已退出登录',
            confirms: () => {
              WindowUtils.getRouter().pushUrl({ url: 'pages/login/LoginPwdPage' })
            }
          }
          H5ShowCommonDialog(context)
        }
        ListenNetworkState.oldNetType = ListenNetworkState.newNetType
      }
    });
​
    //无网络切换到有网络时
    currentNet.on("netAvailable", (data) => {
​
      if (CommonConstants.ISLOGIN) {
        LoginTool.logOut(false, false)
​
        let context: DialogContents = {
          title: "提示",
          message: '网络发生变化,已退出登录',
          confirms: () => {
            WindowUtils.getRouter().pushUrl({ url: 'pages/login/LoginPwdPage' })
          }
        }
        H5ShowCommonDialog(context)
      }
    });
  }
}
相关推荐
柒儿吖3 小时前
m4宏处理器在鸿蒙PC上的应用指南
华为·harmonyos
讯方洋哥5 小时前
初探HarmonyOS应用
华为·harmonyos
C雨后彩虹6 小时前
任务总执行时长
java·数据结构·算法·华为·面试
深海的鲸同学 luvi7 小时前
【HarmonyOS】个性化应用图标动态切换详解
华为·harmonyos
奔跑的露西ly8 小时前
【HarmonyOS NEXT】ohpm 安装依赖失败(@finclip 包找不到)问题复盘与解决方案
华为·harmonyos
余生H8 小时前
时光小铺鸿蒙商城上架全复盘 - 鸿蒙2025领航者闯关.成长升级路
华为·harmonyos·鸿蒙2025领航者闯关
鸭蛋超人不会飞10 小时前
鸿蒙OS学习与项目搭建报告
harmonyos
LRX_19892710 小时前
华为设备配置练习(七)VRRP 配置
服务器·网络·华为
waeng_luo10 小时前
[鸿蒙2025领航者闯关]图标资源统一管理
harmonyos·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结
挨踢攻城10 小时前
华为项目管理的43210法则
华为·项目管理·信息系统项目管理师·pmp·软考高项·华为项目管理·公众号厦门微思网络