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

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

HarmonyOS
2025-01-10 08:09:50
浏览
收藏 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%')
  }
}

请参考: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 如何检测网络是否畅通
255浏览 • 1回复 待解决
HarmonyOS 如何检测没有网络
326浏览 • 1回复 待解决
HarmonyOS 如何检测网络状态
419浏览 • 1回复 待解决
HarmonyOS 怎么判断是否网络
395浏览 • 1回复 待解决
HarmonyOS 如何检测webview滚动是否触底
669浏览 • 1回复 待解决
HarmonyOS 是否检测到app签名
383浏览 • 1回复 待解决
HarmonyOS 如何判断当前网络是否可用
576浏览 • 1回复 待解决
HarmonyOS 是否有人脸活体检测API支持
253浏览 • 1回复 待解决
HarmonyOS 如何监听网络从无到--
232浏览 • 1回复 待解决