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