查询网络连接状态,api12
import { connection } from '@kit.NetworkKit';
export enum NetType {
CELLULAR = 0, //蜂窝网络
WIFI = 1, //WIFI
ETHERNET = 2, //以太网网络
VPN = 3, //VPN
None = 4 //不可用
}
export class NetAddress {
address: string = "";
port?: number = 0;
ipv4: boolean = true;
ipv6: boolean = false;
}
export class NetCapbbilities {
/*
* 网络发生改变
* */
public static netStatusDidCahnge(callback: (status: NetType) => void) {
let con = connection.createNetConnection();
con.register(() => {
});
con.on("netLost",(info: connection.NetHandle) => {
callback(NetType.None);
})
con.on("netAvailable",(info) => {
let status = NetCapbbilities.currentNetType();
callback(status);
});
}
/*
* 连接网络类型
* */
public static currentNetType(): NetType {
let has = connection.hasDefaultNetSync();
if (has) {
let h = connection.getDefaultNetSync();
let c = connection.getNetCapabilitiesSync(h);
let bearerTypes: connection.NetBearType = c.bearerTypes[0];
switch (bearerTypes) {
case connection.NetBearType.BEARER_CELLULAR:
return NetType.CELLULAR;
case connection.NetBearType.BEARER_WIFI:
return NetType.WIFI;
case connection.NetBearType.BEARER_ETHERNET:
return NetType.ETHERNET;
case connection.NetBearType.BEARER_VPN:
return NetType.VPN;
}
}
return NetType.None;
}
/*
* 获取ip地址
* */
public static getIp(): NetAddress {
if (NetCapbbilities.currentNetType() == NetType.None) {
return new NetAddress();
}
let h = connection.getDefaultNetSync();
let p = connection.getConnectionPropertiesSync(h);
let address = p.linkAddresses[0];
let res = new NetAddress();
res.address = address.address.address;
res.port = address.address.port;
res.ipv4 = address.address.family == 1;
res.ipv6 = address.address.family == 2;
return res;
}
}