中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
需要对网络从关闭到开启的变化情况下进行事件处理,请问应该如何在页面中监听网络变化
微信扫码分享
export default class EntryAbility extends UIAbility { // netCon : connection.NetConnection = connection.createNetConnection(); onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // MainAbility onCreate, isStageMode: true console.log('MainAbility onCreate, isStageMode: ' + this.context.stageMode); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); // let netCon1 : connection.NetConnection = connection.createNetConnection(); //开启监听事件 this.netCon.register((error: BusinessError) => { console.log("test register" + JSON.stringify(error)); }); } //网络状态监听 netCon: connection.NetConnection = connection.createNetConnection(); connTest() { //监听网络是否可用 this.netCon.on('netAvailable', (data) => { console.log("test net status netAvailable" + JSON.stringify(data)) }) this.netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => { console.log("test netCapabilitiesChange" + JSON.stringify(data)); }); this.netCon.on("netLost", (data) => { console.log("test netLost" + JSON.stringify(data)) }) this.netCon.on('netUnavailable', (data) => { console.log("test net status netUnavailable" + JSON.stringify(data)) }) } onDestroy() { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); this.netCon.unregister((error: BusinessError) => { console.log("test unregister" + JSON.stringify(error)); }); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); }); }