1# 事件通知开发常见问题 2 3 4## 如何封装一个通用的commonEvent工具类(API 9) 5 6**问题现象** 7 8封装一个通用的commonEvent工具类:希望在创建订阅者的同时注册一个自定义的回调函数,然后在收到事件通知的同时能调用这个自定义的回调函数。 9 10**解决措施** 11 12``` 13import commonEvent from '@ohos.commonEventManager'; 14 15export class SubscribeEvent { 16 private static subscriber = null 17 // 自定义的回调函数变量 18 private static callback = null 19 /** 20 * 创建订阅者 21 * @param subscribeInfo 订阅事件 22 * @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 * 订阅公共事件 39 * @param 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('订阅:' + 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('发布') 78 .fontSize(30) 79 .fontWeight(FontWeight.Bold) 80 .onClick(() => { 81 //公共事件相关信息 82 let options = { 83 code: 0, //公共事件的初始代码 84 data: "initial data",//公共事件的初始数据 85 isOrdered: true //有序公共事件 86 } 87 //发布公共事件回调 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 //发布公共事件 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**参考链接** 111 112[公共事件模块](../reference/apis-basic-services-kit/js-apis-commonEventManager.md) 113 114## 如何让事件只在一个UIAbility实例中传递(API 9) 115 116**问题现象** 117 118应该如何实现事件只在一个UIAbility实例中订阅和触发 119 120**解决措施** 121 122在UIAbility中使用EventHub订阅事件,EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件的能力 123 124**代码示例** 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 // 结果: 135 // eventFunc is called,undefined,undefined 136 this.context.eventHub.emit('myEvent'); 137 // 结果: 138 // eventFunc is called,1,undefined 139 this.context.eventHub.emit('myEvent', 1); 140 // 结果: 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**参考链接** 151 152[使用EventHub进行数据](../application-models/uiability-data-sync-with-ui.md#使用eventhub进行数据通信) 153 154 155## 如何实现点击Notification通知打开App功能(API 9) 156 157**解决措施** 158 159通过配置Notification.publish发布通知接口的参数NotificationRequest中wantAgent属性实现 160 161**代码示例** 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", // 自己应用的bundleName 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: "测试标题", 185 text: "测试内容", 186 } 187 }, 188 id: 1, 189 wantAgent: wantAgent 190 }) 191} 192``` 193 194**参考链接** 195 196[Notification](../reference/apis-notification-kit/js-apis-notificationManager.md)、[WantAgent](../reference/apis-ability-kit/js-apis-app-ability-wantAgent.md) 197 198 199## 调用notificationManager.publish发布通知失败(API 9) 200 201**问题现象** 202 203发布通知后,无错误日志信息,通知栏没有通知显示 204 205**解决措施** 206 207发布通知时,需要在真机端系统设置中,开启对应应用的通知开关,然后才能在通知栏中看到发布的通知。 208 209手动开启步骤:设置 > 通知和状态栏 > 应用名称 > 允许通知。 210 211也可通过接口notificationManager.requestEnableNotification()来弹窗让用户授权(仅弹一次)。 212