HarmonyOS 如何检测是否有网络链接

在应用中如何检测网络连接的变化?例如,在wifi和蜂窝网络均无法使用的时候,进行提示,在重新连接上之后,取消提示

HarmonyOS
2025-01-10 08:09:50
1145浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

// 创建NetConnection对象
let netCon: connection.NetConnection = connection.createNetConnection();

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  aboutToAppear(): void {
    netCon.register((error: BusinessError) => {
      console.log(JSON.stringify(error));
    });

    netCon.on('netAvailable', (data: connection.NetHandle) => {
      console.info("netAvailable Succeeded to get data: " + JSON.stringify(data));
    });

    netCon.on('netLost', (data: connection.NetHandle) => {
      console.info("netLost Succeeded to get data: " + JSON.stringify(data));
    });
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('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.

请参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-net-connection-V5#netconnection

设备从无网络到有网络会触发netAvailable事件、netCapabilitiesChange事件和netConnectionPropertiesChange事件;

设备从有网络到无网络状态会触发netLost事件;

设备从WiFi到蜂窝会触发netLost事件(WiFi丢失)之后触发 netAvailable事件(蜂窝可用);

分享
微博
QQ
微信
回复
2025-01-10 10:31:28


相关问题
HarmonyOS 如何检测网络是否畅通
594浏览 • 1回复 待解决
HarmonyOS 如何检测网络状态
746浏览 • 1回复 待解决
HarmonyOS 如何检测没有网络
665浏览 • 1回复 待解决
HarmonyOS 怎么判断是否网络
814浏览 • 1回复 待解决
HarmonyOS 如何检测webview滚动是否触底
984浏览 • 1回复 待解决
如何检测应用当前版本是否最新?
220浏览 • 0回复 待解决
HarmonyOS 如何判断当前网络是否可用
1018浏览 • 1回复 待解决
HarmonyOS 是否检测到app签名
810浏览 • 1回复 待解决
HarmonyOS 是否有人脸活体检测API支持
720浏览 • 1回复 待解决