华为HarmonyOS打造开放、合规的广告生态 - 插屏广告

场景介绍

插屏广告是一种在应用开启、暂停或退出时以全屏或半屏的形式弹出的广告形式,展示时机巧妙避开用户对应用的正常体验,尺寸大,曝光效果好。

接口说明

接口名 描述
loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void 请求单广告位广告,通过AdRequestParams、AdOptions进行广告请求参数设置,通过AdLoadListener监听广告请求回调。
showAd(ad: Advertisement, options: AdDisplayOptions, context?: common.UIAbilityContext): void 展示广告,通过AdDisplayOptions进行广告展示参数设置。

开发步骤

  1. 获取OAID。

    如果想要为用户更精准的推送广告,可以在请求参数AdRequestParams中添加oaid属性。

    如何获取OAID参见获取OAID信息

    说明

    使用以下示例中提供的测试广告位必须先获取OAID信息。

  2. 请求单广告位广告。

    需要先创建一个AdLoader对象,通过AdLoader的loadAd方法请求广告,最后通过AdLoadListener来监听广告的加载状态。

    请求广告关键参数如下所示:

    请求广告参数名 类型 必填 说明
    adType number 请求广告类型,插屏广告类型为12。
    adId string 广告位ID。 * 如果仅调测广告,可使用测试广告位ID:testb4znbuh3n2。 * 如果要接入正式广告,则需要申请正式的广告位ID。可在应用发布前进入流量变现官网,点击"开始变现",登录鲸鸿动能媒体服务平台进行申请,具体操作详情请参见展示位创建
    oaid string 开放匿名设备标识符,用于精准推送广告。不填无法获取到个性化广告。

    示例代码如下所示:

    复制代码
    1. import { advertising, identifier } from '@kit.AdsKit';
    2. import { common } from '@kit.AbilityKit';
    3. import { hilog } from '@kit.PerformanceAnalysisKit';
    4. import { BusinessError } from '@kit.BasicServicesKit';
    5. @Entry
    6. @Component
    7. struct Index {
    8. private ads: Array<advertising.Advertisement> = [];
    9. private context = getContext(this) as common.UIAbilityContext;
    10. private oaid: string = '';
    11. aboutToAppear() {
    12. try {
    13. // 使用Promise回调方式获取OAID
    14. identifier.getOAID().then((data) => {
    15. this.oaid = data;
    16. hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in getting adsIdentifierInfo by promise');
    17. }).catch((error: BusinessError) => {
    18. hilog.error(0x0000, 'testTag', '%{public}s', `Failed to get adsIdentifierInfo, message: ${error.message}`);
    19. })
    20. } catch (error) {
    21. hilog.error(0x0000, 'testTag', '%{public}s', `Catch err, code: {error.code}, message: {error.message}`);
    22. }
    23. }
    24. build() {
    25. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
    26. Row() {
    27. Button('requestAd').onClick(() => {
    28. let load: advertising.AdLoader = new advertising.AdLoader(this.context);
    29. this.requestAd(load);
    30. }).width('45%')
    31. }
    32. }
    33. }
    34. private requestAd(adLoader: advertising.AdLoader): void {
    35. const adRequestParam: advertising.AdRequestParams = {
    36. // 广告类型:插屏广告
    37. adType: 12,
    38. // 'testb4znbuh3n2'为测试专用的广告位ID,App正式发布时需要改为正式的广告位ID
    39. adId: 'testb4znbuh3n2',
    40. // 开放匿名设备标识符
    41. oaid: this.oaid
    42. };
    43. const adOption: advertising.AdOptions = {
    44. // 设置是否请求非个性化广告
    45. nonPersonalizedAd: 0,
    46. // 是否允许流量下载0:不允许,1:允许,不设置以广告主设置为准
    47. allowMobileTraffic: 0,
    48. // 是否希望根据 COPPA 的规定将您的内容视为面向儿童的内容: -1默认值,不确定 0不希望 1希望
    49. tagForChildProtection: -1,
    50. // 是否希望按适合未达到法定承诺年龄的欧洲经济区 (EEA) 用户的方式处理该广告请求: -1默认值,不确定 0不希望 1希望
    51. tagForUnderAgeOfPromise: -1,
    52. // 设置广告内容分级上限: W: 3+,所有受众 PI: 7+,家长指导 J:12+,青少年 A: 16+/18+,成人受众
    53. adContentClassification: 'A'
    54. };
    55. const adLoaderListener: advertising.AdLoadListener = {
    56. onAdLoadFailure: (errorCode: number, errorMsg: string) => {
    57. hilog.error(0x0000, 'testTag', '%{public}s',
    58. `Failed to request ad, message: {errorMsg}, error code: {errorCode}`);
    59. },
    60. onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
    61. hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in requesting ad!');
    62. this.ads = [];
    63. this.ads.push(...ads);
    64. },
    65. };
    66. adLoader.loadAd(adRequestParam, adOption, adLoaderListener);
    67. }
    68. }
  3. 事件订阅。

    开发者需要在App中订阅com.huawei.hms.pps.action.PPS_INTERSTITIAL_STATUS_CHANGED事件来监听插屏广告页面变化并接收插屏信息。示例代码中的订阅方法registerPPSReceiver()需要在每次展示广告前调用 。

    在订阅到公共事件后,可以从CommonEventData的parameters参数中使用"interstitial_ad_status"作为key值获取插屏广告页面变化状态。

    示例代码如下所示:

    复制代码
    1. import { commonEventManager, BusinessError } from '@kit.BasicServicesKit';
    2. import { hilog } from '@kit.PerformanceAnalysisKit';
    3. const KEY_INTERSTITIAL_STATUS = 'interstitial_ad_status';
    4. export class InterstitialAdStatusHandler {
    5. // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
    6. private subscriber: commonEventManager.CommonEventSubscriber | null = null;
    7. // 订阅方法,需要在每次展示广告前调用
    8. public registerPPSReceiver(): void {
    9. if (this.subscriber) {
    10. this.unRegisterPPSReceiver();
    11. }
    12. // 订阅者信息
    13. const subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
    14. events: ['com.huawei.hms.pps.action.PPS_INTERSTITIAL_STATUS_CHANGED'],
    15. publisherBundleName: 'com.huawei.hms.adsservice'
    16. };
    17. // 创建订阅者回调
    18. commonEventManager.createSubscriber(subscribeInfo,
    19. (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
    20. if (err) {
    21. hilog.error(0x0000, 'testTag', '%{public}s', `CreateSubscriber error, {err.code}, message: {err.message}}`);
    22. return;
    23. }
    24. hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in creating subscriber');
    25. this.subscriber = commonEventSubscriber;
    26. // 订阅公共事件回调
    27. if (!this.subscriber) {
    28. hilog.warn(0x0000, 'testTag', '%{public}s', 'Need to create subscriber');
    29. return;
    30. }
    31. commonEventManager.subscribe(this.subscriber,
    32. (err: BusinessError, commonEventData: commonEventManager.CommonEventData) => {
    33. if (err) {
    34. hilog.error(0x0000, 'testTag', '%{public}s', `Subscribe error, {err.code}, message: {err.message}`);
    35. } else {
    36. // 订阅者成功接收到公共事件
    37. hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded subscribing data');
    38. // 获取插屏广告页面变化状态
    39. const status: string = commonEventData?.parameters?.[KEY_INTERSTITIAL_STATUS];
    40. switch (status) {
    41. case AdStatus.AD_OPEN:
    42. hilog.info(0x0000, 'testTag', '%{public}s', 'onAdOpen');
    43. break;
    44. case AdStatus.AD_CLICKED:
    45. hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClick');
    46. break;
    47. case AdStatus.AD_CLOSED:
    48. hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClose');
    49. this.unRegisterPPSReceiver();
    50. break;
    51. case AdStatus.AD_VIDEO_START:
    52. hilog.info(0x0000, 'testTag', '%{public}s', 'onAdVideoStart');
    53. break;
    54. case AdStatus.AD_COMPLETED:
    55. hilog.info(0x0000, 'testTag', '%{public}s', 'onAdCompleted');
    56. break;
    57. default:
    58. break;
    59. }
    60. }
    61. });
    62. });
    63. }
    64. // 取消订阅
    65. public unRegisterPPSReceiver(): void {
    66. commonEventManager.unsubscribe(this.subscriber, (err: BusinessError) => {
    67. if (err) {
    68. hilog.error(0x0000, 'testTag', '%{public}s', `Unsubscribe error, {err.code}, message: {err.message}}`);
    69. } else {
    70. hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in unsubscribing');
    71. this.subscriber = null;
    72. }
    73. });
    74. }
    75. }
    76. enum AdStatus {
    77. AD_OPEN = 'onAdOpen',
    78. AD_CLICKED = 'onAdClick',
    79. AD_CLOSED = 'onAdClose',
    80. AD_VIDEO_START = 'onVideoPlayBegin',
    81. AD_COMPLETED = 'onVideoPlayEnd'
    82. }
  4. 展示广告。

    ads为步骤2请求到的广告信息,调用showAd方法来展示广告。示例代码如下所示:

    复制代码
    1. import { advertising } from '@kit.AdsKit';
    2. import { common } from '@kit.AbilityKit';
    3. @Entry
    4. @Component
    5. struct Index {
    6. private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    7. // 步骤2中请求到的广告内容
    8. private ads: Array<advertising.Advertisement> = [];
    9. private displayOptions: advertising.AdDisplayOptions = {
    10. // 插屏广告视频播放是否静音
    11. mute: true
    12. };
    13. build() {
    14. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
    15. Row() {
    16. Button('showAd').onClick(() => {
    17. this.showAd();
    18. }).width('45%')
    19. }
    20. }
    21. }
    22. private showAd() {
    23. // 请在此处自行增加步骤3中的,注册插屏广告状态监听器
    24. // ...
    25. // 此处ads[0]表示请求到的第一个广告,用户根据实际情况选择
    26. advertising.showAd(this.ads[0], this.displayOptions, this.context);
    27. }
    28. }
相关推荐
小诸葛的博客4 小时前
华为ensp实现跨vlan通信
网络·华为·智能路由器
康康这名还挺多6 小时前
鸿蒙HarmonyOS list优化一: list 结合 lazyforeach用法
数据结构·list·harmonyos·lazyforeach
晚秋大魔王10 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——nettle库
linux·开源·harmonyos
python算法(魔法师版)13 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
bestadc15 小时前
鸿蒙 UIAbility组件与UI的数据同步和窗口关闭
harmonyos
枫叶丹416 小时前
【HarmonyOS Next之旅】DevEco Studio使用指南(二十二)
华为·harmonyos·deveco studio·harmonyos next
ax一号街阿楠17 小时前
华为FAT AP配置 真机
网络·华为·智能路由器
吗喽对你问好18 小时前
华为5.7机考第一题充电桩问题Java代码实现
java·华为·排序
乱世刀疤20 小时前
深度 |国产操作系统“破茧而出”:鸿蒙电脑填补自主生态空白
华为·harmonyos
博睿谷IT99_1 天前
华为HCIP-AI认证考试版本更新通知
人工智能·华为