当前位置:   article > 正文

【HarmonyOS】【ArkUI】在Service中使用Emitter_ohos.events.emitter

ohos.events.emitter

 参考资料

1.相关基础知识:触发器Emitter
2.启动服务:ServiceAbility开发

开发步骤

第一步:开发界面,界面内容由一个按钮组件+文本组件构成,然后在按钮组件中添加点击事件,开启服务。代码如下:

  1. import featureAbility from "@ohos.ability.featureAbility"
  2. import emitter from '@ohos.events.emitter';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State text: string = ""
  7. aboutToAppear() {
  8. var innerEvent = { eventId: 1002 }
  9. emitter.on(innerEvent, (eventData) => {
  10. let result = eventData.data.sum
  11. this.text = result
  12. console.log("计算的结果为:" + result)
  13. })
  14. }
  15. aboutToDisappear(){
  16. emitter.off(1002)
  17. }
  18. build() {
  19. Column() {
  20. Row() {
  21. Button("计算数组的和", { type: ButtonType.Normal })
  22. }
  23. .width("100%")
  24. .justifyContent(FlexAlign.Center)
  25. .height("20%")
  26. .alignItems(VerticalAlign.Center)
  27. .backgroundColor("#d5d5d5")
  28. .onClick(() => {
  29. console.log("按钮被点击")
  30. featureAbility.startAbility({
  31. want: {
  32. deviceId: "",
  33. bundleName: "com.zwc.myapplication",
  34. abilityName: "com.zwc.myapplication.ServiceAbility1",
  35. }
  36. })
  37. })
  38. Column() {
  39. Text("数组的和为:" + this.text)
  40. .fontSize(40)
  41. .fontColor(Color.Green)
  42. .width("100%")
  43. .textAlign(TextAlign.Center)
  44. }
  45. .width("100%")
  46. .height("80%")
  47. .backgroundColor("#FFCCaa")
  48. }
  49. }
  50. }

第二步:新建服务类,在服务中完成数组计算,把值通过触发器传递至界面显示
一定要在config.json文件中,在module模块下配置触发器权限:

  1. "reqPermissions": [
  2. {
  3. "name": "ohos.permission.PUBLISH_AGENT_REMINDER"
  4. }
  5. ],

然后编写服务类,通过触发器的emmit方法把计算后的值发送至界面:
emitter.emit(innerEvent, eventData)

  1. import hilog from '@ohos.hilog';
  2. import emitter from '@ohos.events.emitter';
  3. export default {
  4. onCommand(want, startId) {
  5. hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.DEBUG);
  6. hilog.debug(0x0000, 'testTag', '%{public}s', 'ServiceAbility onCommand');
  7. let myArrays: Array<number> = [10, 20, 30, 40, 50, 60]
  8. let sum: number = 0;
  9. for (let i = 0;i < myArrays.length; i++) {
  10. sum += myArrays[i]
  11. }
  12. hilog.debug(0x0000, 'testTag', '%{public}s', '数据的和是:' + sum);
  13. var innerEvent = {
  14. eventId: 1002
  15. }
  16. var eventData = {
  17. data: {
  18. 'sum': sum
  19. },
  20. priority: emitter.EventPriority.HIGH
  21. }
  22. hilog.debug(0x0000, 'testTag', '%{public}s', '发射器:' + JSON.stringify(eventData.data));
  23. emitter.emit(innerEvent, eventData)
  24. hilog.debug(0x0000, 'testTag', '%{public}s', '发成功');
  25. }
  26. };

运行结果

8f0968b59b2d6cd87f15cb5bfe2b8966_1595x884.gif%40900-0-90-f.gif

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/318582
推荐阅读
相关标签
  

闽ICP备14008679号