参考资料
1.相关基础知识:触发器Emitter2.启动服务:ServiceAbility开发
开发步骤
第一步:开发界面,界面内容由一个按钮组件+文本组件构成,然后在按钮组件中添加点击事件,开启服务。代码如下:
import featureAbility from "@ohos.ability.featureAbility" import emitter from '@ohos.events.emitter'; @Entry @Component struct Index { @State text: string = "" aboutToAppear() { var innerEvent = { eventId: 1002 } emitter.on(innerEvent, (eventData) => { let result = eventData.data.sum this.text = result console.log("计算的结果为:" + result) }) } aboutToDisappear(){ emitter.off(1002) } build() { Column() { Row() { Button("计算数组的和", { type: ButtonType.Normal }) } .width("100%") .justifyContent(FlexAlign.Center) .height("20%") .alignItems(VerticalAlign.Center) .backgroundColor("#d5d5d5") .onClick(() => { console.log("按钮被点击") featureAbility.startAbility({ want: { deviceId: "", bundleName: "com.zwc.myapplication", abilityName: "com.zwc.myapplication.ServiceAbility1", } }) }) Column() { Text("数组的和为:" + this.text) .fontSize(40) .fontColor(Color.Green) .width("100%") .textAlign(TextAlign.Center) } .width("100%") .height("80%") .backgroundColor("#FFCCaa") } } }
第二步:新建服务类,在服务中完成数组计算,把值通过触发器传递至界面显示一定要在config.json文件中,在module模块下配置触发器权限:
"reqPermissions": [ { "name": "ohos.permission.PUBLISH_AGENT_REMINDER" } ],
然后编写服务类,通过触发器的emmit方法把计算后的值发送至界面:emitter.emit(innerEvent, eventData)
import hilog from '@ohos.hilog'; import emitter from '@ohos.events.emitter'; export default { onCommand(want, startId) { hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.DEBUG); hilog.debug(0x0000, 'testTag', '%{public}s', 'ServiceAbility onCommand'); let myArrays: Array<number> = [10, 20, 30, 40, 50, 60] let sum: number = 0; for (let i = 0;i < myArrays.length; i++) { sum += myArrays[i] } hilog.debug(0x0000, 'testTag', '%{public}s', '数据的和是:' + sum); var innerEvent = { eventId: 1002 } var eventData = { data: { 'sum': sum }, priority: emitter.EventPriority.HIGH } hilog.debug(0x0000, 'testTag', '%{public}s', '发射器:' + JSON.stringify(eventData.data)); emitter.emit(innerEvent, eventData) hilog.debug(0x0000, 'testTag', '%{public}s', '发成功'); } };
运行结果
欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh
标签:
留言评论