reference material:
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-network-61
@ohos.net connection (network connection management)
Network connection management provides basic capabilities for managing networks, including priority management of multiple network connections such as WiFi/cellular/Ethernet, network quality assessment, subscribing to default/specified network connection status changes, querying network connection information, DNS resolution, and other functions.
connection.createNetConnection
Create a NetConnection object, netSpecifier, to specify the various features of the network to be focused on; Timeout is the timeout period (in milliseconds); NetSpecifier is a necessary condition for timeout, and if neither is present, it indicates attention to the default network.
Idea: By using the ability of @ ohos.net.connection, when the network connection status changes, judge whether the current network can access the Internet, and store the judgment results in AppStorage. When it is necessary to determine the network connection status, directly obtain the results from AppStore.
prerequisite:
Modify the modular.json5 configuration file to add network permissions:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.GET_NETWORK_INFO"
}
]
Add the NetworkUtil utility class:
import { connection } from "@kit.NetworkKit";
import { BusinessError } from "@kit.BasicServicesKit";
import { promptAction } from "@kit.ArkUI";
import { hilog } from "@kit.PerformanceAnalysisKit";
export class NetworkUtil {
private static netConnection: connection.NetConnection | undefined = undefined;
public static JUDGE_NET_TAG: string = 'NetworkUtil.netConnection.isUseful';
/**
* 工具注册。
* 作用:监控网络状态
*/
static register() {
if (NetworkUtil.netConnection === undefined) {
NetworkUtil.init();
}
}
/**
* 获取网络连接状态
* @returns boolean
* true: 有网络
* false: 无网络
*/
static getStatus(): boolean {
return NetworkUtil.judgeHasNet()
}
static continueWhenNetUsable(callback: () => void) {
if (NetworkUtil.getStatus()) {
callback()
} else {
promptAction.showToast({
message: 'The network is not worked, please check your network',
duration: 2000
});
}
}
private static init() {
NetworkUtil.netConnection = connection.createNetConnection();
NetworkUtil.netConnection.register(() => {
Logger.info('connection register success');
});
NetworkUtil.netConnection.on('netAvailable', (data) => {
Logger.info('NetworkUtil netAvailable ');
AppStorage.setOrCreate(NetworkUtil.JUDGE_NET_TAG, NetworkUtil.judgeHasNet());
});
NetworkUtil.netConnection.on('netUnavailable', () => {
Logger.info('NetworkUtil netUnavailable ');
AppStorage.setOrCreate(NetworkUtil.JUDGE_NET_TAG, NetworkUtil.judgeHasNet());
});
NetworkUtil.netConnection.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
Logger.info('NetworkUtil netCapabilitiesChange');
AppStorage.setOrCreate(NetworkUtil.JUDGE_NET_TAG, NetworkUtil.judgeHasNet());
});
// 订阅网络连接信息变化事件。调用register后,才能接收到此事件通知
NetworkUtil.netConnection.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
Logger.info('NetworkUtil netConnectionPropertiesChange');
AppStorage.setOrCreate(NetworkUtil.JUDGE_NET_TAG, NetworkUtil.judgeHasNet());
});
NetworkUtil.netConnection.on('netLost', () => {
Logger.info('NetworkUtil netLost');
AppStorage.setOrCreate(NetworkUtil.JUDGE_NET_TAG, NetworkUtil.judgeHasNet());
});
}
private static judgeHasNet(): boolean {
try { // 获取当前网络连接
let netHandle = connection.getDefaultNetSync();
// 0-100 为系统预留的连接
if (!netHandle || netHandle.netId < 100) {
return false;
}
// 获取连接的属性
let netCapability = connection.getNetCapabilitiesSync(netHandle);
let cap = netCapability.networkCap;
if (!cap) {
return false;
}
for (let em of cap) {
if (connection.NetCap.NET_CAPABILITY_VALIDATED === em) {
return true;
}
}
} catch (e) {
let err = e as BusinessError;
Logger.info('get netInfo error :' + JSON.stringify(err));
}
return false;
}
}
class Logger{
static info(...args: string[]){
hilog.info(0x0000, '-logger-', getFormat(args), args);
}
}
function getFormat(args: string[]) {
let format = ''
for (let i = 0; i < args.length; i++) {
if (i == 0) {
format = '%{public}s'
} else {
format += ', %{public}s'
}
}
return format
}
Sample code for using the NetworkUtilPage page:
import { NetworkUtil } from '../../utils/NetworkUtil'
import { promptAction } from '@kit.ArkUI';
@Entry
@Component
struct NetworkUtilPage {
//用法一:通过状态管理实时获取网络状态
@StorageProp(NetworkUtil.JUDGE_NET_TAG)
isNetConnectionUseful: boolean = true;
aboutToAppear(): void {
NetworkUtil.register()
}
build() {
Column({ space: 10 }) {
Text('NetworkUtil Page')
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text() {
Span('watch network status is ')
Span(JSON.stringify(this.isNetConnectionUseful))
.fontColor(this.isNetConnectionUseful ? Color.Green : Color.Red)
.fontWeight(600)
}
Button('getNetworkStatus').onClick(() => {
//用法二:获取当前的网络状态
const status = NetworkUtil.getStatus()
promptAction.showToast({
message: 'The network status is ' + JSON.stringify(status),
duration: 5000
});
})
Button('continue When Net Usable').onClick(() => {
//用法三:有网络继续后续动作,无网则中断后续动作并且弹窗提示用户设置网络。
NetworkUtil.continueWhenNetUsable(() => {
//当网络中断,弹窗提示用户设置网络且不执行后续动作
//当网络可用,继续执行
promptAction.showToast({
message: 'have net, continue!',
duration: 5000
});
})
})
}
.height('100%')
.width('100%')
}
}
Top comments (0)