import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
export class SNMDemo {
constructor() {
this.init();
}
init() {
console.info('init start');
let netSpecifier: connection.NetSpecifier = {
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR, connection.NetBearType.BEARER_WIFI,
connection.NetBearType.BEARER_ETHERNET],
// 指定网络能力为Internet
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
},
};
// 指定超时时间为10s(默认值为0)
let timeout = 10 * 1000;
// 创建NetConnection对象
let conn = connection.createNetConnection(netSpecifier, timeout);
// 订阅指定网络状态变化的通知
conn.register((err: BusinessError, data: void) => {
if (err) {
console.error(`监听网络状态失败 ${JSON.stringify(err)}`)
}
});
// 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户
conn.on('netAvailable', ((data: connection.NetHandle) => {
console.info(`netAvailable ${data.netId}`);
connection.getNetCapabilities(data, (error, data) => {
if (error) {
console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`)
return;
}
const netType = [...data.bearerTypes].sort().join(',');
console.info(`netAvailable type change ${netType}`);
})
}));
// 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户
conn.on('netUnavailable', ((data: void) => {
console.info(`netUnavailable`);
}));
console.info(`init end`);
}
}
之后在页面中创建
@Entry
@Component
struct Index {
private demo = new SNMDemo();
}
目前只有刚创建的netAvailable回调,之后关闭打开wifi、移动网络没有任何回调触发。
请参考示例如下修改,关闭网络监听用netLost: