1# Event and Notification Development 2 3## How do I encapsulate a commonEvent utility class? 4 5Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) 6 7**Problem** 8 9A 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. 10 11**Solution** 12 13``` 14import commonEvent from '@ohos.commonEventManager'; 15 16export class SubscribeEvent { 17 private static subscriber = null 18 // Custom callback function 19 private static callback = null 20 /** 21 * Create a subscriber. 22 * @param subscribeInfo Indicates the event to subscribe to. 23 * @callback Indicates the custom callback. 24 */ 25 static createSubscriber(subscribeInfo, callback:(a,b)=>void) { 26 this.callback = callback 27 commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { 28 if (err) { 29 console.error('CreateSubscriberCallBack err = ' + JSON.stringify(err)) 30 } else { 31 this.subscriber = subscriber; 32 this.subscribe(this.subscriber) 33 console.info('Create subscriber succeed') 34 } 35 }) 36 } 37 38 /** 39 * Subscribe to a common event. 40 * @param subscriber Indicates the subscriber. 41 */ 42 private static subscribe(subscriber) { 43 if (subscriber != null) { 44 commonEvent.subscribe(subscriber, (err, data) => { 45 if (err) { 46 console.error('subscribe err = ' + JSON.stringify(err)) 47 } else { 48 console.info('SubscribeCallBack data= ' + JSON.stringify(data)) 49 this.callback('hello callback', data) 50 } 51 }) 52 } else { 53 console.info("Need create subscriber") 54 } 55 } 56} 57 58@Entry 59@Component 60struct Faq10_1 { 61 @State message: string = '' 62 63 build() { 64 Row() { 65 Column() { 66 Text ('Subscribe:' + this.message) 67 .fontSize(30) 68 .fontWeight(FontWeight.Bold) 69 .onClick(() => { 70 let subscribeInfo = { 71 events: ["myEvent"] 72 }; 73 let callback = (a,b) => { 74 this.message = a 75 } 76 SubscribeEvent.createSubscriber(subscribeInfo,callback) 77 }) 78 Text ('Publish') 79 .fontSize(30) 80 .fontWeight(FontWeight.Bold) 81 .onClick(() => { 82 // Attributes of a common event. 83 let options = { 84 code: 0, // Result code of the common event. 85 data: "initial data",// Result data of the common event. 86 isOrdered: true // The common event is an ordered one. 87 } 88 // Callback for common event publication. 89 function publishCB(err) { 90 if (err) { 91 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 92 } else { 93 console.info("publish"); 94 } 95 } 96 // Publish a common event. 97 try { 98 commonEvent.publish("myEvent", options, publishCB); 99 } catch (err) { 100 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 101 } 102 }) 103 } 104 .width('100%') 105 } 106 .height('100%') 107 } 108} 109``` 110 111**Reference** 112 113[@ohos.commonEventManager (Common Event)](../reference/apis/js-apis-commonEventManager.md) 114 115## How do I make events be transferred in only one UIAbility instance? 116 117Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) 118 119**Problem** 120 121Events need to be subscribed to and triggered only in one UIAbility instance. 122 123**Solution** 124 125Use 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. 126 127**Example** 128 129``` 130import UIAbility from '@ohos.app.ability.UIAbility'; 131 export default class EntryAbility extends UIAbility { 132 onForeground() { 133 this.context.eventHub.on('myEvent', this.eventFunc); 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 eventFunc(argOne, argTwo) { 145 console.log('eventFunc is called, ${argOne}, ${argTwo}'); 146 }} 147``` 148 149**Reference** 150 151[Using EventHub for Data Synchronization](../application-models/uiability-data-sync-with-ui.md#using-eventhub-for-data-synchronization). 152 153## How do I implement a click-to-open-application feature in the notification? 154 155Applicable to: OpenHarmony 3.1 Beta 5 (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/js-apis-notificationManager.md) and [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) 197 198## What should I do if calling notificationManager.publish fails? 199 200Applicable to: OpenHarmony 3.2 Beta5 201 202**Problem** 203 204After a notification is published, no error log is displayed, and no notification is displayed in the notification panel. 205 206**Solution** 207 208Before 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. 209 210To manually enable the notification feature, choose **Settings** > **Notification & status bar** > *Application name* > **Allow notifications**. 211 212You can also call the **notificationManager.requestEnableNotification\(\)** API to display a dialog box (only once) to prompt the user to enable the feature. 213