RewardAd.ets 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import { advertising } from '@kit.AdsKit';
  2. import { common } from '@kit.AbilityKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { BusinessError, commonEventManager, emitter } from '@kit.BasicServicesKit';
  5. import { AdStatus } from '../constants';
  6. import { YTLog, YTToast } from '../../../../Index';
  7. import { IBestToast } from '@ibestservices/ibest-ui';
  8. const KEY_REWARD_DATA = "reward_ad_data";
  9. const KEY_REWARD_STATUS = "reward_ad_status";
  10. export class RewardAd {
  11. private ads: Array<advertising.Advertisement> = [];
  12. private uIContext: common.UIAbilityContext
  13. private load: advertising.AdLoader
  14. // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
  15. private subscriber: commonEventManager.CommonEventSubscriber | null = null;
  16. private displayOptions: advertising.AdDisplayOptions = {
  17. // 激励广告视频播放是否静音
  18. mute: true
  19. };
  20. private isReward = false
  21. constructor(uIContext: common.UIAbilityContext) {
  22. this.uIContext = uIContext
  23. this.load = new advertising.AdLoader(this.uIContext);
  24. this.requestAndShowAd(this.load)
  25. }
  26. // 订阅方法,需要在每次展示广告前调用
  27. public registerPPSReceiver(): void {
  28. if (this.subscriber) {
  29. this.unRegisterPPSReceiver();
  30. }
  31. // 订阅者信息
  32. const subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  33. events: ["com.huawei.hms.pps.action.PPS_REWARD_STATUS_CHANGED"],
  34. // publisherBundleName被设置为"com.huawei.hms.adsservice",这意味着只有来自该包名的事件才会被订阅者接受和处理。
  35. // 如果没有明确声明publisherBundleName,那么订阅者可能会收到来自其它包名的伪造事件,从而导致安全性问题或误导。
  36. publisherBundleName: "com.huawei.hms.adsservice"
  37. };
  38. // 创建订阅者回调
  39. commonEventManager.createSubscriber(subscribeInfo, (err: BusinessError, commonEventSubscriber:
  40. commonEventManager.CommonEventSubscriber) => {
  41. if (err) {
  42. hilog.error(0x0000, 'testTag', '%{public}s',
  43. `createSubscriber error, code: ${err.code}, message: ${err.message}`);
  44. return;
  45. }
  46. hilog.info(0x0000, 'testTag', '%{public}s', `Succeeded in creating subscriber`);
  47. this.subscriber = commonEventSubscriber;
  48. // 订阅公共事件回调
  49. if (!this.subscriber) {
  50. hilog.warn(0x0000, 'testTag', '%{public}s', `Need create subscriber`);
  51. return;
  52. }
  53. commonEventManager.subscribe(this.subscriber, (err: BusinessError, commonEventSubscriber:
  54. commonEventManager.CommonEventData) => {
  55. if (err) {
  56. hilog.error(0x0000, 'testTag', '%{public}s', `Subscribe error, code: ${err.code}, message: ${err.message}`);
  57. } else {
  58. hilog.info(0x0000, 'testTag', '%{public}s', 'Subscribe data');
  59. const status: string = commonEventSubscriber?.parameters?.[KEY_REWARD_STATUS];
  60. switch (status) {
  61. case AdStatus.AD_OPEN:
  62. hilog.info(0x0000, 'testTag', '%{public}s', `onAdOpen`);
  63. //关闭弹窗
  64. IBestToast.hide()
  65. YTToast.getInstance().hide()
  66. break;
  67. case AdStatus.AD_CLICKED:
  68. hilog.info(0x0000, 'testTag', '%{public}s', `onAdClick`);
  69. break;
  70. case AdStatus.AD_CLOSED:
  71. hilog.info(0x0000, 'testTag', '%{public}s', `onAdClose`);
  72. this.unRegisterPPSReceiver();
  73. if (this.isReward) {
  74. this.isReward = false
  75. if (AppStorage.get<number>('RewardNum')! < 5) {
  76. setTimeout(() => {
  77. // YTToast.getInstance().getReward({ number: 500 })
  78. }, 500)
  79. }
  80. }
  81. break;
  82. case AdStatus.AD_REWARDED:
  83. const rewardData: Record<string, string | number> = commonEventSubscriber?.parameters?.[KEY_REWARD_DATA];
  84. const rewardType: string = rewardData?.rewardType as string;
  85. const rewardAmount: number = rewardData?.rewardAmount as number;
  86. //奖励位置
  87. this.isReward = true
  88. YTLog.info('发送奖励')
  89. emitter.emit('getReward')
  90. break;
  91. case AdStatus.AD_VIDEO_START:
  92. hilog.info(0x0000, 'testTag', '%{public}s', `onAdVideoStart`);
  93. break;
  94. case AdStatus.AD_COMPLETED:
  95. hilog.info(0x0000, 'testTag', '%{public}s', `onAdCompleted`);
  96. break;
  97. default:
  98. IBestToast.hide()
  99. IBestToast.show({ message: '加载失败' })
  100. break;
  101. }
  102. }
  103. });
  104. });
  105. }
  106. // 取消订阅
  107. public unRegisterPPSReceiver(): void {
  108. commonEventManager.unsubscribe(this.subscriber, (err: BusinessError) => {
  109. if (err) {
  110. hilog.error(0x0000, 'testTag', '%{public}s', `Unsubscribe error, code: ${err.code}, message: ${err.message}`);
  111. } else {
  112. hilog.info(0x0000, 'testTag', '%{public}s', `Succeeded in unsubscribing`);
  113. this.subscriber = null;
  114. }
  115. });
  116. }
  117. private requestAndShowAd(adLoader: advertising.AdLoader): void {
  118. const adRequestParam: advertising.AdRequestParams = {
  119. // 广告类型:激励广告
  120. adType: 7,
  121. // 'testx9dtjwj8hp'为测试专用的广告位ID,应用正式发布时需要改为正式的广告位ID
  122. adId: 'testx9dtjwj8hp',
  123. };
  124. const adOption: advertising.AdOptions = {
  125. // 设置是否请求非个性化广告
  126. nonPersonalizedAd: 0,
  127. // 是否允许流量下载0:不允许,1:允许,不设置以广告主设置为准
  128. allowMobileTraffic: 0,
  129. // 是否希望根据 COPPA 的规定将您的内容视为面向儿童的内容: -1默认值,不确定 0不希望 1希望
  130. tagForChildProtection: -1,
  131. // 是否希望按适合未达到法定承诺年龄的欧洲经济区 (EEA) 用户的方式处理该广告请求: -1默认值,不确定 0不希望 1希望
  132. tagForUnderAgeOfPromise: -1,
  133. // 设置广告内容分级上限: W: 3+,所有受众 PI: 7+,家长指导 J:12+,青少年 A: 16+/18+,成人受众
  134. adContentClassification: 'A'
  135. };
  136. const adLoaderListener: advertising.AdLoadListener = {
  137. onAdLoadFailure: (errorCode: number, errorMsg: string) => {
  138. setTimeout(() => {
  139. IBestToast.hide()
  140. setTimeout(() => {
  141. IBestToast.show({ message: '加载失败' })
  142. }, 100)
  143. }, 1000)
  144. },
  145. onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
  146. hilog.info(0x0000, 'testTag', '%{public}s', `Succeeded in requesting ad`);
  147. this.ads.push(...ads);
  148. this.showAd()
  149. },
  150. };
  151. adLoader.loadAd(adRequestParam, adOption, adLoaderListener);
  152. }
  153. //展示广告
  154. private showAd() {
  155. // 请在此处自行增加步骤2中的,注册激励广告状态监听器
  156. this.registerPPSReceiver()
  157. // 此处ads[0]表示请求到的第一个广告,用户根据实际情况选择
  158. advertising.showAd(this.ads[0], this.displayOptions, this.uIContext);
  159. }
  160. }