zhangbo1_wd

新增网络监听、网络管理相关

... ... @@ -43,3 +43,9 @@ export { ErrorToastUtils } from './src/main/ets/utils/ErrorToastUtils'
export { EmitterUtils } from './src/main/ets/utils/EmitterUtils'
export { EmitterEventId } from './src/main/ets/utils/EmitterEventId'
export { NetworkUtil } from './src/main/ets/utils/NetworkUtil'
export { NetworkManager } from './src/main/ets/network/NetworkManager'
export { NetworkType } from './src/main/ets/network/NetworkType'
... ...
import connection from '@ohos.net.connection';
import { BusinessError } from '@ohos.base';
import { Logger } from '../utils/Logger';
import { EmitterUtils } from '../utils/EmitterUtils';
import { EmitterEventId } from '../utils/EmitterEventId';
import { NetworkType } from './NetworkType';
const TAG = 'NetworkManager'
/**
* 网络管理类
*/
export class NetworkManager {
private netCon: connection.NetConnection | null = null;
private static instance: NetworkManager;
private networkType: NetworkType = NetworkType.TYPE_UNKNOWN
public static getInstance(): NetworkManager {
if (!NetworkManager.instance) {
NetworkManager.instance = new NetworkManager();
}
return NetworkManager.instance;
}
public init() {
// 初始化
if (this.netCon) {
// 拦截重复初始化
return
}
this.networkMonitorRegister()
}
public release() {
this.networkMonitorUnregister()
}
private constructor() {
}
private networkMonitorRegister() {
this.netCon = connection.createNetConnection();
this.netCon.register((error) => {
if (error) {
Logger.error(TAG, 'register error:' + error.message);
return;
}
Logger.info(TAG, 'register success');
})
this.netCon.on('netAvailable', (data: connection.NetHandle) => {
Logger.info(TAG, 'netAvailable, data is: ' + JSON.stringify(data))
})
this.netCon.on('netBlockStatusChange', (data: connection.NetBlockStatusInfo) => {
Logger.info(TAG, 'netBlockStatusChange, data is: ' + JSON.stringify(data))
// TODO 网络阻塞,是否创建新的网络、提示
})
this.netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
Logger.info(TAG, 'netCapabilitiesChange, data is: ' + JSON.stringify(data))
this.parseData(data)
// 可能多次通知
EmitterUtils.sendEvent(EmitterEventId.NETWORK_CONNECTED, JSON.stringify(this.networkType))
})
this.netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
Logger.info(TAG, 'netConnectionPropertiesChange, data is: ' + JSON.stringify(data))
})
this.netCon.on('netUnavailable', ((data: void) => {
Logger.info(TAG, 'netUnavailable, data is: ' + JSON.stringify(data))
}));
this.netCon.on('netLost', ((data: connection.NetHandle) => {
Logger.info(TAG, 'netLost, data is: ' + JSON.stringify(data))
// TODO 断网
EmitterUtils.sendEvent(EmitterEventId.NETWORK_DISCONNECTED)
this.networkType = NetworkType.TYPE_NONE
}))
}
private networkMonitorUnregister() {
if (this.netCon) {
this.netCon.unregister((error: BusinessError) => {
if (error) {
Logger.error(TAG, 'unregister error:' + error.message);
return;
}
Logger.info(TAG, 'unregister success');
})
}
}
/**
* @deprecated
*/
private getNetworkMessage(netHandle: connection.NetHandle) {
connection.getNetCapabilities(netHandle, (error, netCap) => {
if (error) {
Logger.error(TAG, 'getNetCapabilities error:' + error.message);
return;
}
let netType = netCap.bearerTypes;
this.reset(netType)
})
}
private reset(netType: Array<connection.NetBearType>) {
if (netType == null) {
return
}
for (let i = 0; i < netType.length; i++) {
if (netType[i] === 0) {
// 蜂窝网
this.networkType = NetworkType.TYPE_CELLULAR
} else if (netType[i] === 1) {
// Wi-Fi网络
this.networkType = NetworkType.TYPE_WIFI
} else {
// 以太网网络
this.networkType = NetworkType.TYPE_ETHERNET
}
}
}
/**
* 获取网络类型,网络监听网络变化刷新类型,这里优先返回变量
*/
public getNetType(): NetworkType {
if (this.networkType != NetworkType.TYPE_UNKNOWN) {
return this.networkType
}
return this.getNetTypeSync()
}
/**
* 同步获取网络类型,耗时
*/
public getNetTypeSync(): NetworkType {
let netHandle = connection.getDefaultNetSync();
let netCapabilities = connection.getNetCapabilitiesSync(netHandle)
this.reset(netCapabilities.bearerTypes)
return this.networkType;
}
private parseData(data: connection.NetCapabilityInfo) {
// 解析网络信息
this.reset(data.netCap.bearerTypes)
}
}
\ No newline at end of file
... ...
/**
* 网络管理类
*/
export enum NetworkType {
// 未知
TYPE_UNKNOWN = -1,
// 无网络
TYPE_NONE = 0,
// wifi
TYPE_WIFI = 1,
// 蜂窝网
TYPE_CELLULAR = 2,
// 以太网
TYPE_ETHERNET = 3,
}
\ No newline at end of file
... ...
... ... @@ -3,6 +3,10 @@
*/
export enum EmitterEventId {
// 通知登出,事件id
FORCE_USER_LOGIN_OUT = 1
FORCE_USER_LOGIN_OUT = 1,
// 网络连接成功,事件id
NETWORK_CONNECTED = 2,
// 网络断开,事件id
NETWORK_DISCONNECTED = 3,
}
... ...
import { NetworkManager } from '../network/NetworkManager'
import { NetworkType } from '../network/NetworkType'
/**
* 网络相关工具类
* 要实时监听网络,需要添加注册函数{例:src/main/ets/entryability/EntryAbility.ets:32}
*/
export class NetworkUtil {
/**
* 网络环境:0:无网 1:WiFi 2:2G 3:3G 4:4G 5:5G,暂时只识别出蜂窝网
* 扩展6-以太网
*/
static TYPE_NONE = '0'
static TYPE_WIFI = '1'
static TYPE_CELLULAR = '5'
// TODO 以太网,手机不涉及
static TYPE_ETHERNET = '6'
static getNetworkType(): string {
let type = NetworkManager.getInstance().getNetType()
return NetworkUtil.parseType(type)
}
static parseType(type: NetworkType): string {
switch (type) {
case NetworkType.TYPE_UNKNOWN:
case NetworkType.TYPE_NONE:
return NetworkUtil.TYPE_NONE;
case NetworkType.TYPE_WIFI:
return NetworkUtil.TYPE_WIFI;
case NetworkType.TYPE_CELLULAR:
return NetworkUtil.TYPE_CELLULAR;
case NetworkType.TYPE_ETHERNET:
return NetworkUtil.TYPE_ETHERNET;
default:
return NetworkUtil.TYPE_NONE;
}
}
}
\ No newline at end of file
... ...
... ... @@ -8,6 +8,11 @@
"tablet",
"2in1"
],
"deliveryWithInstall": true
"deliveryWithInstall": true,
"requestPermissions": [
{
"name": "ohos.permission.GET_NETWORK_INFO"
}
]
}
}
\ No newline at end of file
... ...
... ... @@ -4,7 +4,16 @@ import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { registerRouter } from 'wdRouter';
import { SPHelper, StringUtils, WindowModel } from 'wdKit';
import {
EmitterEventId,
EmitterUtils,
Logger,
NetworkManager,
NetworkType,
SPHelper,
StringUtils,
WindowModel
} from 'wdKit';
import { HttpUrlUtils, WDHttp } from 'wdNetwork';
export default class EntryAbility extends UIAbility {
... ... @@ -12,15 +21,30 @@ export default class EntryAbility extends UIAbility {
SPHelper.init(this.context);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
registerRouter();
NetworkManager.getInstance().init()
WDHttp.initHttpHeader()
const spHostUrl = SPHelper.default.getSync('hostUrl', '') as string
if (StringUtils.isNotEmpty(spHostUrl)) {
HttpUrlUtils.hostUrl = spHostUrl
}
// 注册监听网络连接
EmitterUtils.receiveEvent(EmitterEventId.NETWORK_CONNECTED, ((str?: string) => {
let type: NetworkType | null = null
if (str) {
type = JSON.parse(str) as NetworkType
}
Logger.info('network connected: ' + type?.toString())
}))
// 注册监听网络断开
EmitterUtils.receiveEvent(EmitterEventId.NETWORK_DISCONNECTED, (() => {
Logger.info('network disconnected')
}))
}
onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
NetworkManager.getInstance().release()
}
onWindowStageCreate(windowStage: window.WindowStage): void {
... ...