• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import CommonEventManager from '@ohos.commonEventManager'
17import promptAction from '@ohos.promptAction'
18import Logger from '../../../../../entry/src/main/ets/model/Logger'
19import Base from '@ohos.base'
20
21const SEND_DATA:string = 'usual.event.SEND_DATA'
22
23@Entry
24@Component
25struct Index {
26  build() {
27    Row() {
28      Column() {
29        Button() {
30          Text($r('app.string.publish'))
31            .fontSize(22)
32            .fontColor($r('app.color.white'))
33        }
34        .type(ButtonType.Capsule)
35        .margin({ top: 20 })
36        .backgroundColor('#007DFF')
37        .width('80%')
38        .height('5%')
39        .onClick(() => {
40          // 公共事件相关信息
41          let options: CommonEventManager.CommonEventPublishData = {
42            code: 0, // 公共事件的初始代码
43            bundleName: '',
44            data: getContext(this).resourceManager.getStringSync($r('app.string.publish_data')),
45            isOrdered: true // 有序公共事件
46          }
47
48          // 发布公共事件回调
49          let publishCallback = (err: Base.BusinessError) => {
50            if (err) {
51              Logger.error(`publish failed ${JSON.stringify(err)}`);
52            } else {
53              try {
54                promptAction.showToast({
55                  message: $r('app.string.publish_success'),
56                  duration: 2000,
57                });
58              } catch (error) {
59                Logger.error(`showToast args error code is ${(error as Base.BusinessError).code}, message is ${(error as Base.BusinessError).message}`);
60              }
61              Logger.info('publish success');
62            }
63          }
64
65          // 发布公共事件
66          try {
67            CommonEventManager.publish(SEND_DATA, options, publishCallback);
68          } catch (err) {
69            Logger.error(`publish failed, catch error ${JSON.stringify(err)}`);
70          }
71        })
72      }
73      .width('100%')
74    }
75    .height('100%')
76    .backgroundColor($r('app.color.background_light_gray'))
77    .id('btnPublish')
78  }
79}