1# Event and Notification Development
2
3
4## How do I encapsulate a commonEvent utility class? (API version 9)
5
6**Problem**
7
8A commonEvent utility class needs to be encapsulated for the following purpose: Register a custom callback function when creating a subscriber, and then call the custom callback function when receiving an event notification.
9
10**Solution**
11
12```
13import commonEvent from '@ohos.commonEventManager';
14
15export class SubscribeEvent {
16  private static subscriber = null
17  // Custom callback function
18  private static callback = null
19  /**
20   * Create a subscriber.
21   * @param subscribeInfo Indicates the event to subscribe to.
22   * @callback Indicates the custom callback.
23   */
24  static createSubscriber(subscribeInfo, callback:(a,b)=>void) {
25    this.callback = callback
26    commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
27      if (err) {
28        console.error('CreateSubscriberCallBack err = ' + JSON.stringify(err))
29      } else {
30        this.subscriber = subscriber;
31        this.subscribe(this.subscriber)
32        console.info('Create subscriber succeed')
33      }
34    })
35  }
36
37  /**
38   * Subscribe to a common event.
39   * @param subscriber Indicates the subscriber.
40   */
41  private static subscribe(subscriber) {
42    if (subscriber != null) {
43      commonEvent.subscribe(subscriber, (err, data) => {
44        if (err) {
45          console.error('subscribe err = ' + JSON.stringify(err))
46        } else {
47          console.info('SubscribeCallBack data= ' + JSON.stringify(data))
48          this.callback('hello callback', data)
49        }
50      })
51    } else {
52      console.info("Need create subscriber")
53    }
54  }
55}
56
57@Entry
58@Component
59struct Faq10_1 {
60  @State message: string = ''
61
62  build() {
63    Row() {
64      Column() {
65        Text ('Subscribe:' + this.message)
66          .fontSize(30)
67          .fontWeight(FontWeight.Bold)
68          .onClick(() => {
69            let subscribeInfo = {
70              events: ["myEvent"]
71            };
72            let callback = (a,b) => {
73              this.message = a
74            }
75            SubscribeEvent.createSubscriber(subscribeInfo,callback)
76          })
77        Text ('Publish')
78          .fontSize(30)
79          .fontWeight(FontWeight.Bold)
80          .onClick(() => {
81            // Attributes of a common event.
82            let options = {
83              code: 0,    // Result code of the common event.
84              data: "initial data",// Result data of the common event.
85              isOrdered: true  // The common event is an ordered one.
86            }
87            // Callback for common event publication.
88            function publishCB(err) {
89              if (err) {
90                console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
91              } else {
92                console.info("publish");
93              }
94            }
95            // Publish a common event.
96            try {
97              commonEvent.publish("myEvent", options, publishCB);
98            } catch (err) {
99              console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
100            }
101          })
102      }
103      .width('100%')
104    }
105    .height('100%')
106  }
107}
108```
109
110**Reference**
111
112[@ohos.commonEventManager (Common Event)](../reference/apis-basic-services-kit/js-apis-commonEventManager.md)
113
114## How do I make events be transferred in only one UIAbility instance? (API version 9)
115
116**Problem**
117
118Events need to be subscribed to and triggered only in one UIAbility instance.
119
120**Solution**
121
122Use the API in the **EventHub** module of the UIAbility to subscribe to events. The **EventHub** module offers the event center, which provides the API for subscribing to, unsubscribing from, and triggering events.
123
124**Example**
125
126```
127import UIAbility from '@ohos.app.ability.UIAbility';
128 export default class EntryAbility extends UIAbility {
129    onCreate() {
130        this.context.eventHub.on('myEvent', this.eventFunc);
131    }
132
133    onDestroy() {
134        // Result
135        // eventFunc is called,undefined,undefined
136        this.context.eventHub.emit('myEvent');
137        // Result
138        // eventFunc is called,1,undefined
139        this.context.eventHub.emit('myEvent', 1);
140        // Result
141        // eventFunc is called,1,2
142        this.context.eventHub.emit('myEvent', 1, 2);
143    }
144
145     eventFunc(argOne, argTwo) {
146        console.log('eventFunc is called, ${argOne}, ${argTwo}');
147    }}
148```
149
150**Reference**
151
152[Using EventHub for Data Synchronization](../application-models/uiability-data-sync-with-ui.md#using-eventhub-for-data-synchronization).
153
154
155## How do I implement a click-to-open-application feature in the notification? (API version 9)
156
157**Solution**
158
159You can implement this feature by setting the **wantAgent** attribute in the **NotificationRequest** parameter of the **Notification.publish** API.
160
161**Example**
162
163```
164import notificationManager from '@ohos.notificationManager';
165import WantAgent from '@ohos.app.ability.wantAgent';
166
167async function publishNotification() {
168  let wantAgentInfo = {
169    wants: [
170      {
171        bundleName: "com.example.webuseragent", // Bundle name of the target application.
172        abilityName: "EntryAbility",
173      }
174    ],
175    operationType: WantAgent.OperationType.START_ABILITIES,
176    requestCode: 1,
177  }
178  const wantAgent = await WantAgent.getWantAgent(wantAgentInfo)
179  let contentType = notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT;
180  await notificationManager.publish({
181    content: {
182      contentType: contentType,
183      normal: {
184        title: "Test Title",
185        text: "Test content",
186      }
187    },
188    id: 1,
189    wantAgent: wantAgent
190  })
191}
192```
193
194**Reference**
195
196[Notification](../reference/apis-notification-kit/js-apis-notificationManager.md) and [WantAgent](../reference/apis-ability-kit/js-apis-app-ability-wantAgent.md)
197
198
199## What should I do if calling notificationManager.publish fails?
200
201**Problem**
202
203After a notification is published, no error log is displayed, and no notification is displayed in the notification panel.
204
205**Solution**
206
207Before publishing a notification, you must enable the notification feature for your application in the system settings of the real device so that the notification can be viewed in the notification panel.
208
209To manually enable the notification feature, choose **Settings** > **Notification & status bar** > *Application name* > **Allow notifications**.
210
211You can also call the **notificationManager.requestEnableNotification()** API to display a dialog box (only once) to prompt the user to enable the feature.
212