【高心星出品】
文章目录
Ability与Page数据传递
基于当前的应用模型,可以通过以下几种方式来实现UIAbility组件与UI之间的数据同步。
- 使用EventHub进行数据通信:在基类Context中提供了EventHub对象,可以通过发布订阅方式来实现事件的传递。在事件传递前,订阅者需要先进行订阅,当发布者发布事件时,订阅者将接收到事件并进行相应处理。
- 使用AppStorage/LocalStorage进行数据同步:ArkUI提供了AppStorage和LocalStorage两种应用级别的状态管理方案,可用于实现应用级别和UIAbility级别的数据同步。
Page向Ability传递数据
EventHub为UIAbility组件提供了事件机制,使它们能够进行订阅、取消订阅和触发事件等数据通信能力。
在基类Context中,提供了EventHub对象,可用于在UIAbility组件实例内通信。使用EventHub实现UIAbility与UI之间的数据通信需要先获取EventHub对象,本章节将以此为例进行说明。
下面案例实现:页面点击按钮发送颜色给ability,从而修改ability的窗口背景色。
EntryAbility代码
typescript
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// 注册event_01事件监听
this.context.eventHub.on('event_01',(data:Record<string,Object>)=>{
// 获取页面传递的数据 设置窗口背景颜色
this.context.windowStage.getMainWindowSync().setWindowBackgroundColor(data!.color as string)
})
}
onDestroy(): void {
//关闭监听
this.context.eventHub.off('event_01')
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/eventpage', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
}
eventpage页面代码
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Eventpage {
@State message: string = 'Hello World';
private context:common.UIAbilityContext=getContext(this) as common.UIAbilityContext
build() {
Column(){
Button('向EntryAbility发送数据更改背景颜色')
.width('60%')
.onClick(()=>{
// 提交数据
this.context.eventHub.emit('event_01',{color:'#ff0000'})
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
Ability向Page传递数据
ArkUI提供了AppStorage和LocalStorage两种应用级别的状态管理方案,可用于实现应用级别和UIAbility级别的数据同步。使用这些方案可以方便地管理应用状态,提高应用性能和用户体验。其中,AppStorage是一个全局的状态管理器,适用于多个UIAbility共享同一状态数据的情况;而LocalStorage则是一个局部的状态管理器,适用于单个UIAbility内部使用的状态数据。
下面一个案例:在ability获取窗口可布局界面的宽度和高度(窗口高度-通知栏高度)
EntryAbility代码
javascript
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AppStorageV2, window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// 注册event_01事件监听
this.context.eventHub.on('event_01',(data:Record<string,Object>)=>{
// 获取页面传递的数据 设置窗口背景颜色
this.context.windowStage.getMainWindowSync().setWindowBackgroundColor(data!.color as string)
})
}
onDestroy(): void {
//关闭监听
this.context.eventHub.off('event_01')
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
// 获取窗口可布局的宽度和高度
let win=windowStage.getMainWindowSync()
// 获得通知栏区域
let notifybar=win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect
let width=win.getWindowProperties().windowRect.width
let height=win.getWindowProperties().windowRect.height-notifybar.height
// 保存到appstorage中
AppStorage.setOrCreate('width', width);
AppStorage.setOrCreate('height', height);
windowStage.loadContent('pages/eventpage', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
}
eventpage页面代码
javascript
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Eventpage {
@State message: string = 'Hello World';
// 获取ability传过来的宽度和高度 单位是px
@StorageProp('width') wd: number = 0
@StorageProp('height') ht: number = 0
private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
build() {
Column() {
Button('向EntryAbility发送数据更改背景颜色')
.width('60%')
.onClick(() => {
// 提交数据
this.context.eventHub.emit('event_01', { color: '#ff0000' })
})
Column() {
Text('宽度为: ' + this.wd).width('100%').fontSize(20)
Text('高度为: ' + this.ht).width('100%').fontSize(20)
}
// 设置组件的宽和高
.width(this.wd / 2 + 'px')
.height(this.ht / 3 + 'px')
.border({ width: 3, color: Color.Red, style: BorderStyle.Dashed })
.justifyContent(FlexAlign.Center)
.margin(20)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
order({ width: 3, color: Color.Red, style: BorderStyle.Dashed })
.justifyContent(FlexAlign.Center)
.margin(20)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}