HarmonyOS 怎么监听网络断网和网络重新连接

HarmonyOS
2024-12-25 17:14:23
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

监听网络推荐使用netConnect,参考demo如下参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/net-connection-manager-V5

import connection from '@ohos.net.connection';
import { BusinessError } from "@ohos.base";
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  onPageShow(): void {
    this.init();
  }

  init(){
    let netCon: connection.NetConnection = connection.createNetConnection();
    netCon.register((error: BusinessError) => {
      if(error==undefined){
        hilog.info(0x0000,"网络状态","注册成功")
      }else {
        hilog.info(0x0000,"网络状态","注册失败 error is %s",JSON.stringify(error))
      }


    });

    // 订阅网络可用事件。调用register后,才能接收到此事件通知
    netCon.on('netAvailable', (data: connection.NetHandle) => {
      hilog.info(0x0000,"网络状态",'网络状态可用 ' + JSON.stringify(data));
    });
    // 订阅网络不可用事件。调用register后,才能接收到此事件通知
    netCon.on('netUnavailable', () => {
      hilog.info(0x0000,"网络状态",'网络状态不可用1 ');
    });
    netCon.on('netLost', () => {
      hilog.info(0x0000,"网络状态",'网络状态不可用2 ');
    });

    // 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知
    netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
      hilog.info(0x0000,"网络状态","Succeeded to get data: " + JSON.stringify(data));
    });

    connection.getDefaultNet().then((netHandle)=>{
      connection.reportNetDisconnected(netHandle).then(()=> {
        hilog.info(0x0000,"网络状态",'reportNetDisconnected ');
      });
    });

  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
分享
微博
QQ
微信
回复
2024-12-25 19:19:26
相关问题
HarmonyOS 网络连接监听问题
1019浏览 • 1回复 待解决
HarmonyOS 网络监听api怎么
753浏览 • 1回复 待解决
HarmonyOS 怎么实现网络切换的监听
845浏览 • 1回复 待解决
HarmonyOS 监听网络错误
571浏览 • 1回复 待解决
HarmonyOS网络监听问题
911浏览 • 1回复 待解决
HarmonyOS 判断网络是否连接
586浏览 • 1回复 待解决
HarmonyOS websocket后如何重连
1138浏览 • 1回复 待解决
HarmonyOS 网络变化监听失效
786浏览 • 1回复 待解决
HarmonyOS ipv6网络支持情况
674浏览 • 1回复 待解决
HarmonyOS 网络监听回调多次
859浏览 • 1回复 待解决
HarmonyOS connection监听网事件
959浏览 • 1回复 待解决
获取当前网络连接能力
1723浏览 • 1回复 待解决
获取netHandle网络连接信息
1435浏览 • 1回复 待解决
网络地址建立socket连接
1557浏览 • 1回复 待解决
wifi连接候选网络报错{code : 2501000 }
1130浏览 • 1回复 待解决