
回复
一、使用生命周期管理优化ArkTS内存
组件的生命周期,指的是组件自身的一些可自执行的方法,这些方法会在特殊的时间点或遇到一些特殊页面行为时被自动触发而执行。
(一)原理介绍
在开发过程中,开发人员可以通过管理对象的生命周期来释放资源、销毁对象、优化ArkTS内存。
在UIAbility组件生命周期中,调用对应生命周期的方法,创建或销毁资源。如在Create或Foreground方法中创建资源,在Background、Destroy方法中销毁对应的资源。
在页面生命周期中,调用对应生命周期的方法,创建或销毁资源。如在onPageShow方法中创建资源,在onPageHide方法中销毁对应的资源。
在组件生命周期中,调用对应生命周期的方法,创建或销毁资源。如在aboutToAppear方法中创建资源,在aboutToDisappear方法中销毁不再使用的对象、注销不再使用的订阅事件。
调用组件自带的方法,创建、销毁组件。如调用XComponent的onDestroy方法。
(二)aboutToDisappear中销毁订阅事件
aboutToDisappear函数会在组件析构销毁之前执行。如下案例所示,在使用完网络管理的网络连接模块后,取消订阅默认网络状态变化的通知。
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { CommonConstant as Const } from '../common/Constant';
import { promptAction } from '@kit.ArkUI';
import { Logger } from '../utils/Logger';
@Entry
@Component
struct Index {
@State networkId: string = Const.NETWORK_ID;
@State netMessage: string = Const.INIT_NET_MESSAGE;
@State connectionMessage: string = Const.INIT_CONNECTION_MESSAGE;
@State netStateMessage: string = '';
@State hostName: string = '';
@State ip: string = '';
private controller: TabsController = new TabsController();
private netHandle: connection.NetHandle | null = null;
private netCon: connection.NetConnection | null = null;
scroller: Scroller = new Scroller();
aboutToDisappear(): void {
// unregister NetConnection
this.unUseNetworkRegister;
}
build() {
Column() {
Text($r('app.string.network_title'))
.fontSize($r('app.float.title_font_size'))
.fontWeight(FontWeight.Bold)
.textAlign(TextAlign.Start)
.margin({ left: Const.WebConstant_TEN_PERCENT })
.width(Const.WebConstant_FULL_WIDTH)
Column() {
Row() {
Text(Const.MONITOR_TITLE)
.fontSize($r('app.float.font_size'))
.margin($r('app.float.md_padding_margin'))
.fontWeight(FontWeight.Medium)
Blank()
Toggle({ type: ToggleType.Switch, isOn: false })
.selectedColor(Color.Blue)
.margin({ right: $r('app.float.md_padding_margin') })
.width($r('app.float.area_width'))
.height(Const.WebConstant_BUTTON_HEIGHT)
.onChange((isOn) => {
if (isOn) {
this.useNetworkRegister();
} else {
this.unUseNetworkRegister();
}
})
}
.height($r('app.float.button_height'))
.borderRadius($r('app.float.md_border_radius'))
.margin({ left: $r('app.float.md_padding_margin'), right: $r('app.float.md_padding_margin') })
.width(Const.WebConstant_NINETY_PERCENT)
.backgroundColor($r('app.color.text_background'))
TextArea({ text: this.netStateMessage })
.fontSize($r('app.float.font_size'))
.width(Const.WebConstant_NINETY_PERCENT)
.height(Const.WebConstant_FIVE_HUNDRED)
.margin($r('app.float.md_padding_margin'))
.borderRadius($r('app.float.md_border_radius'))
.textAlign(TextAlign.Start)
.focusOnTouch(false)
Button($r('app.string.clear'))
.fontSize($r('app.float.font_size'))
.width(Const.WebConstant_NINETY_PERCENT)
.height($r('app.float.area_height'))
.margin({
left: $r('app.float.md_padding_margin'),
right: $r('app.float.md_padding_margin'),
bottom: $r('app.float.xxl_padding_margin')
})
.onClick(() => {
this.netStateMessage = '';
})
Blank()
}
.height(Const.WebConstant_FULL_HEIGHT)
.justifyContent(FlexAlign.Start)
}
.width(Const.WebConstant_FULL_WIDTH)
}
getConnectionProperties() {
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
connection.getConnectionProperties(netHandle, (error: BusinessError, connectionProperties: connection.ConnectionProperties) => {
if (error) {
this.connectionMessage = Const.CONNECTION_PROPERTIES_ERROR;
Logger.error('getConnectionProperties error:' + error.code + error.message);
return;
}
this.connectionMessage = Const.CONNECTION_PROPERTIES_INTERFACE_NAME + connectionProperties.interfaceName
+ Const.CONNECTION_PROPERTIES_DOMAINS + connectionProperties.domains
+ Const.CONNECTION_PROPERTIES_LINK_ADDRESSES + JSON.stringify(connectionProperties.linkAddresses)
+ Const.CONNECTION_PROPERTIES_ROUTES + JSON.stringify(connectionProperties.routes)
+ Const.CONNECTION_PROPERTIES_LINK_ADDRESSES + JSON.stringify(connectionProperties.dnses)
+ Const.CONNECTION_PROPERTIES_MTU + connectionProperties.mtu + '\n';
})
});
}
useNetworkRegister() {
this.netCon = connection.createNetConnection();
this.netStateMessage += Const.REGISTER_NETWORK_LISTENER;
this.netCon.register((error) => {
if (error) {
Logger.error('register error:' + error.message);
return;
}
promptAction.showToast({
message: Const.REGISTER_NETWORK_LISTENER_MESSAGE,
duration: 1000
});
})
this.netCon.on('netAvailable', (netHandle) => {
this.netStateMessage += Const.NET_AVAILABLE + netHandle.netId + '\n';
})
this.netCon.on('netBlockStatusChange', (data) => {
this.netStateMessage += Const.NET_BLOCK_STATUS_CHANGE + data.netHandle.netId + '\n';
})
this.netCon.on('netCapabilitiesChange', (data) => {
this.netStateMessage += Const.NET_CAPABILITIES_CHANGE_ID + data.netHandle.netId
+ Const.NET_CAPABILITIES_CHANGE_CAP + JSON.stringify(data.netCap) + '\n';
})
this.netCon.on('netConnectionPropertiesChange', (data) => {
this.netStateMessage += Const.NET_CONNECTION_PROPERTIES_CHANGE_ID + data.netHandle.netId
+ Const.NET_CONNECTION_PROPERTIES_CHANGE_CONNECTION_PROPERTIES + JSON.stringify(data.connectionProperties) + '\n';
})
}
unUseNetworkRegister() {
if (this.netCon) {
this.netCon.unregister((error: BusinessError) => {
if (error) {
Logger.error('unregister error:' + error.message);
return;
}
promptAction.showToast({
message: Const.UNREGISTER_NETWORK_LISTENER_MESSAGE,
duration: 1000
});
this.netStateMessage += Const.UNREGISTER_NETWORK_LISTENER;
})
} else {
this.netStateMessage += Const.UNREGISTER_NETWORK_LISTENER_FAIL;
}
}
}
本文主要引用参考HarmonyOS官方文档