鸿蒙实时监听网络状态变化
·
1. 网络监听流程
步骤1:创建网络连接对象
// 声明网络连接对象
private netConnection: connection.NetConnection | null = null;
// 创建网络连接对象
this.netConnection = connection.createNetConnection();
步骤2:注册网络事件监听器
// 网络变得可用
this.netConnection.on('netAvailable', (data) => {});
// 网络丢失
this.netConnection.on('netLost', (data) => {});
// 网络能力变化
this.netConnection.on('netCapabilitiesChange', (data) => {});
// 网络连接属性变化
this.netConnection.on('netConnectionPropertiesChange', (data) => {});
步骤3:注册监听
this.netConnection.register((err: BusinessError) => {
if (err) {
// 处理错误
return;
}
// 注册成功
});
步骤4:处理网络变化
private handleNetChange() {
const status = NetworkUtils.getNetworkStatus();
// 更新UI状态
}
步骤5:停止监听(在组件销毁时)
this.netConnection.unregister(() => {});
this.netConnection = null;
2. UI状态管理
无网络提示条控制:
@State noneWorkBar: boolean = false;
// 在handleNetChange中更新
this.noneWorkBar = (status === NetworkStatus.NONE);
网络状态显示:
@State networkType: string = '未知';
// 在handleNetChange中更新
this.networkType = 'WiFi'; // 根据实际状态更新
网络事件历史记录:
@State networkHistory: string[] = [];
// 添加新事件
this.networkHistory = [`${timestamp}: ${event}`, ...this.networkHistory.slice(0, 9)];
完整代码
// 引入
import { connection } from '@kit.NetworkKit';
// 自定义无网组件
import NoNetworkBar from './NoNetworkBar';
//错误
import { BusinessError } from '@kit.BasicServicesKit';
//组件内定义变量
...
//是否展示无网提示bar
private netConnection: connection.NetConnection | null = null;
@State noneWorkBar: boolean = false
...
// 停止网络监听
private stopNetMonitoring() {
if (this.netConnection) {
try {
this.netConnection.unregister(() => {
});
this.netConnection = null;
} catch (error) {
const err: BusinessError = error as BusinessError;
}
}
}
//页面销毁时停止网络监听
aboutToDisappear() {
this.stopNetMonitoring();
}
//页面出现时开启网络监听
aboutToAppear(): void {
this.startNetMonitoring();
}
// 处理网络变化
private handleNetChange() {
try {
//先判断网络状态
if (connection.getDefaultNetSync().netId == 0) {
this.noneWorkBar = false
} else {
//无网络状态的页面
this.noneWorkBar = true
}
} catch (error) {
const err: BusinessError = error as BusinessError;
LogManager.debug(TAG, `获取网络状态失败: ${err.code}, ${err.message}`);
}
}
//开启网络监听
startNetMonitoring() {
try {
// 创建网络连接对象
this.netConnection = connection.createNetConnection();
// 监听网络变得可用的状态当。设备从无网络状态转为有网络状态时,这个事件会被触发。
this.netConnection.on('netAvailable', (data) => {
this.handleNetChange();
});
// 监听网络丢失。当设备从有网络状态变为无网络状态时,会触发此事件。
this.netConnection.on('netLost', (data) => {
this.handleNetChange();
});
// 监听网络能力集的变更。每当网络的能力(如数据传输速率、网络类型等)发生变化时,这个回调就会被触发
this.netConnection.on('netCapabilitiesChange', (data) => {
this.handleNetChange();
});
//监听网络连接属性的变化。这包括了网络的连接状态、连接类型以及其他与连接本身相关的属性。例如,如果网络连接从WiFi切换到移动数据,或者连接状态从稳定变为不稳定,都会触发这个回调。
this.netConnection.on('netConnectionPropertiesChange', (data) => {
this.handleNetChange();
});
// 注册监听
this.netConnection.register((err: BusinessError) => {
if (err) {
LogManager.debug(TAG, `注册网络监听失败: ${err.code}, ${err.message}`);
return;
}
LogManager.debug(TAG, '网络监听已注册');
});
} catch (error) {
const err: BusinessError = error as BusinessError;
LogManager.debug(TAG, `创建网络监听失败: ${err.code}, ${err.message}`);
}
}
...
//ui部分:无网时展示无网的提示
if (this.noneWorkBar) {
NoNetworkBar()
.padding({
top: HarmonyUtils.getNavigationBarHeight()
})
.zIndex(10)
}
...
3. 最佳实践建议
-
生命周期管理:
- 在
aboutToAppear中启动监听 - 在
aboutToDisappear中停止监听 - 避免内存泄漏
- 在
-
错误处理:
- 使用try-catch捕获可能的异常
- 记录详细的错误日志
- 提供用户友好的错误提示
-
性能优化:
- 限制历史记录数量(示例中保留最近10条)
- 避免频繁的UI更新
- 使用防抖处理连续的网络变化事件
更多推荐

所有评论(0)