华为HarmonyOS打造开放、合规的广告生态 - 开屏广告
场景介绍
开屏广告是一种在应用启动时且在应用主界面显示之前需要被展示的广告。您需要预先为App设计一张开屏默认的Slogan图片,确保在未获得到开屏广告之前展示默认的Slogan,提供良好的用户体验。
开屏广告分为全屏开屏广告、半屏开屏广告,其中全屏开屏广告展示形式为广告铺满整个页面;半屏开屏广告展示形式会根据媒体页面自定义布局渲染广告、icon和版权信息,一般情况下建议将icon和版权信息展示在广告下方。
接口说明
接口名 | 描述 |
---|---|
loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void | 请求单广告位广告,通过AdRequestParams、AdOptions进行广告请求参数设置,通过AdLoadListener监听广告请求回调。 |
AdComponent(ads: advertising.Advertisement[], displayOptions: advertising.AdDisplayOptions, interactionListener: advertising.AdInteractionListener, @BuilderParam adRenderer?: () => void): void | 展示广告,通过AdDisplayOptions进行广告展示参数设置,通过AdInteractionListener监听广告状态回调。 |
开发步骤
- 获取OAID。
如果想要为用户更精准的推送广告,可以在请求参数AdRequestParams中添加oaid属性。
如何获取OAID参见获取OAID信息。
说明
使用以下示例中提供的测试广告位必须先获取OAID信息。
- 请求单广告位广告。
需要创建一个AdLoader对象,通过AdLoader的loadAd方法请求广告,最后通过AdLoadListener来监听广告的加载状态。测试开屏广告时,需要使用专门的测试广告位来获取测试开屏广告,示例代码中提供了两种开屏广告类型对应的广告位:半屏开屏(图片)(testq6zq98hecj)和全屏开屏(视频)(testd7c5cewoj6),测试广告位ID仅作为调试使用,不可用于广告变现。
请求广告关键参数如下所示:
请求广告参数名
类型
必填
说明
adType
number
是
请求广告类型,开屏广告类型为1。
adId
string
是
广告位ID。
- 如果仅调测广告,可使用测试广告位ID:testq6zq98hecj半屏开屏(图片)和testd7c5cewoj6全屏开屏(视频)。
- 如果要接入正式广告,则需要申请正式的广告位ID。可在应用发布前进入流量变现官网,点击“开始变现”,登录鲸鸿动能媒体服务平台进行申请,具体操作详情请参见展示位创建。
adCount
number
否
广告数量。
返回广告参数名
类型
说明
isFullScreen
boolean
标识返回的广告是否为全屏,true为全屏广告,false为半屏广告。
示例代码如下所示:
说明
请求广告之前需要展示默认的Slogan图片,在请求广告时,在onAdLoadSuccess回调中切换展示广告页面。如果超时没有请求到广告,应用自行跳到默认首页。
- import { router, Prompt } from '@kit.ArkUI';
- import { advertising, identifier } from '@kit.AdsKit';
- import { common } from '@kit.AbilityKit';
- import { hilog } from '@kit.PerformanceAnalysisKit';
- import { BusinessError } from '@kit.BasicServicesKit';
- @Entry
- @Component
- export struct Index {
- private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
- private oaid: string = '';
- // 广告展示参数
- private adDisplayOptions: advertising.AdDisplayOptions = {
- // 是否静音,默认不静音
- mute: false
- }
- // 广告配置
- private adOptions: advertising.AdOptions = {
- // 是否允许流量下载0:不允许,1:允许,不设置以广告主设置为准
- allowMobileTraffic: 0,
- // 是否希望根据 COPPA 的规定将您的内容视为面向儿童的内容: -1默认值,不确定 0不希望 1希望
- tagForChildProtection: -1,
- // 是否希望按适合未达到法定承诺年龄的欧洲经济区 (EEA) 用户的方式处理该广告请求: -1默认值,不确定 0不希望 1希望
- tagForUnderAgeOfPromise: -1,
- // 设置广告内容分级上限: W: 3+,所有受众 PI: 7+,家长指导 J:12+,青少年 A: 16+/18+,成人受众
- adContentClassification: 'A'
- }
- // 开屏视频广告请求参数
- private splashVideoAdReqParams: advertising.AdRequestParams = {
- // 'testd7c5cewoj6'为测试专用的广告位ID,App正式发布时需要改为正式的广告位ID
- adId: 'testd7c5cewoj6',
- adType: AdType.SPLASH_AD,
- adCount: 1,
- oaid: this.oaid
- }
- // 开屏图片广告请求参数
- private splashImageAdReqParams: advertising.AdRequestParams = {
- // 'testq6zq98hecj'为测试专用的广告位ID,App正式发布时需要改为正式的广告位ID
- adId: 'testq6zq98hecj',
- adType: AdType.SPLASH_AD,
- adCount: 1,
- oaid: this.oaid
- }
- aboutToAppear() {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Start to aboutToAppear');
- try {
- // 使用Promise回调方式获取OAID
- identifier.getOAID().then((data: string) => {
- this.oaid = data;
- hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in getting adsIdentifierInfo by promise');
- }).catch((error: BusinessError) => {
- hilog.error(0x0000, 'testTag', '%{public}s',
- `Failed to get adsIdentifierInfo, code: ${error.code}, message: ${error.message}`);
- })
- } catch (error) {
- hilog.error(0x0000, 'testTag', '%{public}s', `Catch err, code: ${error.code}, message: ${error.message}`);
- }
- }
- build() {
- Column() {
- Column() {
- // 跳转到开屏全屏视频广告展示页面
- CustomButton({
- mText: 'splash full screen request', mOnClick: () => {
- this.requestAd(this.splashVideoAdReqParams, this.adOptions);
- }
- });
- // 跳转到开屏半屏图片广告展示页面
- CustomButton({
- mText: 'splash half screen request', mOnClick: () => {
- this.requestAd(this.splashImageAdReqParams, this.adOptions);
- }
- });
- }.width('100%').height('80%').justifyContent(FlexAlign.Center)
- }
- .width('100%')
- .height('100%')
- }
- private requestAd(adReqParams: advertising.AdRequestParams, adOptions: advertising.AdOptions): void {
- // 广告请求回调监听
- const adLoaderListener: advertising.AdLoadListener = {
- // 广告请求失败回调
- onAdLoadFailure: (errorCode: number, errorMsg: string) => {
- hilog.error(0x0000, 'testTag', '%{public}s',
- `Failed to request ad. errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
- Prompt.showToast({
- message: `Failed to request ad, code is: ${errorCode} , errorMsg is: ${errorMsg}`,
- duration: 1000
- });
- },
- // 广告请求成功回调
- onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Succeeded in requesting ad!');
- // 保存请求到的广告内容用于展示
- hilog.info(0x0000, 'testTag', '%{public}s', `ads[0].adType is : ${ads[0].adType}`);
- if (canIUse("SystemCapability.Advertising.Ads")) {
- if (ads[0].adType === AdType.SPLASH_AD) {
- // 调用开屏广告展示页面
- if (ads[0]?.isFullScreen === true) {
- routePage('pages/SplashFullScreenAdPage', ads, this.adDisplayOptions);
- } else {
- routePage('pages/SplashHalfScreenAdPage', ads, this.adDisplayOptions);
- }
- } else {
- hilog.error(0x0000, 'testTag', '%{public}s', 'Error adType');
- }
- }
- }
- };
- // 创建AdLoader广告对象
- const load: advertising.AdLoader = new advertising.AdLoader(this.context);
- // 调用广告请求接口
- hilog.info(0x0000, 'testTag', '%{public}s', 'Request ad!');
- adReqParams.oaid = this.oaid;
- load.loadAd(adReqParams, adOptions, adLoaderListener);
- }
- }
- async function routePage(pageUri: string, ads: Array<advertising.Advertisement | null>,
- displayOptions: advertising.AdDisplayOptions) {
- let options: router.RouterOptions = {
- url: pageUri,
- params: {
- ads: ads,
- displayOptions: displayOptions
- }
- }
- try {
- hilog.info(0x0000, 'testTag', '%{public}s', `RoutePage: ${pageUri}`);
- router.pushUrl(options);
- } catch (error) {
- hilog.error(0x0000, 'testTag', '%{public}s',
- `Failed to routePage callback, code: ${error.code}, msg: ${error.message}`);
- }
- }
- export enum AdType {
- // 开屏广告的类型
- SPLASH_AD = 1
- }
- @Component
- export struct CustomButton {
- private mText: string | Resource = '';
- private mHeight: number = 40;
- private mOnClick: (event?: ClickEvent) => void = (): void => {
- };
- build() {
- Column() {
- Button(this.mText)
- .backgroundColor('#d3d4d6')
- .fontSize(20)
- .fontColor('#000')
- .fontWeight(FontWeight.Normal)
- .align(Alignment.Center)
- .type(ButtonType.Capsule)
- .width('90%')
- .height(this.mHeight)
- .margin({ top: 10, bottom: 5 })
- .onClick(this.mOnClick);
- }
- }
- }
- 展示广告。
说明
1、由在步骤2请求广告中获取的isFullScreen参数判断展示全屏或者半屏广告,同时媒体可在AdComponent中绘制自身的半屏部分,可参考展示半屏代码。
2、在枚举的AdStatus状态中,媒体可根据各种状态来进行下一步操作,如在AD_CLOSED时展示首页。
3、目前只支持展示竖屏广告。
在您的页面中使用AdComponent组件展示开屏广告。示例代码如下所示:
您需要在entry/src/main/resources/base/profile/main_pages.json文件中添加页面,如下图所示。
展示半屏广告:
- import { Prompt, router } from '@kit.ArkUI';
- import { advertising, AdComponent } from '@kit.AdsKit';
- import { hilog } from '@kit.PerformanceAnalysisKit';
- @Entry
- @Component
- export struct SplashHalfScreenAdPage {
- private ads: Array<advertising.Advertisement> = [];
- private displayOptions?: advertising.AdDisplayOptions;
- aboutToAppear() {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Start to splashHalfScreenAdPage aboutToAppear');
- const params: Record<string, Object> = router.getParams() as Record<string, Object>;
- if (params && params.ads as Array<advertising.Advertisement> &&
- params.displayOptions as advertising.AdDisplayOptions) {
- this.ads = params.ads as Array<advertising.Advertisement>;
- this.displayOptions = params.displayOptions as advertising.AdDisplayOptions;
- } else {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Router params are empty');
- }
- }
- build() {
- Column() {
- // 运行在提供方进程里
- AdComponent({
- ads: this.ads, displayOptions: this.displayOptions,
- interactionListener: {
- onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
- switch (status) {
- case AdStatus.AD_OPEN:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdOpen');
- Prompt.showToast({
- message: 'splash ad open',
- duration: 1000
- });
- break;
- case AdStatus.AD_CLICKED:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdClick');
- Prompt.showToast({
- message: 'splash ad click',
- duration: 1000
- });
- break;
- case AdStatus.AD_CLOSED:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdClose');
- Prompt.showToast({
- message: 'splash ad close',
- duration: 1000
- });
- router.replaceUrl({
- url: 'pages/Index',
- })
- break;
- }
- }
- }
- })
- .width('100%')
- .height('87%')
- // 展示媒体自定义icon、应用名称、版权信息
- Column({}) {
- Row() {
- Image($r('app.media.video')).width(24).height(24).margin({ right: 8 })
- Text($r('app.string.video')).fontColor('#1A1A1A').fontSize(16).width(32).height(21)
- }.margin({ bottom: 8 })
- Column() {
- Text($r('app.string.copyright')).fontColor('#1A1A1A').fontSize(9).height(15)
- }
- }.width('100%').height('100%')
- }
- }
- }
- export enum AdStatus {
- AD_OPEN = 'onAdOpen',
- AD_CLICKED = 'onAdClick',
- AD_CLOSED = 'onAdClose'
- }
展示全屏广告:
- import { Prompt, router } from '@kit.ArkUI';
- import { advertising, AdComponent } from '@kit.AdsKit';
- import { hilog } from '@kit.PerformanceAnalysisKit';
- const TAG = 'Ads Demo-SplashFullScreenAdPage';
- @Entry
- @Component
- export struct SplashFullScreenAdPage {
- private ads: Array<advertising.Advertisement> = [];
- private displayOptions?: advertising.AdDisplayOptions;
- aboutToAppear() {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Start to splashFullScreenAdPage aboutToAppear');
- const params: Record<string, Object> = router.getParams() as Record<string, Object>;
- if (params && params.ads as Array<advertising.Advertisement> &&
- params.displayOptions as advertising.AdDisplayOptions) {
- this.ads = params.ads as Array<advertising.Advertisement>;
- this.displayOptions = params.displayOptions as advertising.AdDisplayOptions;
- } else {
- hilog.info(0x0000, 'testTag', '%{public}s', 'Router params are empty');
- }
- }
- build() {
- Column() {
- // 运行在提供方进程里
- AdComponent({
- ads: this.ads, displayOptions: this.displayOptions,
- interactionListener: {
- onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
- switch (status) {
- case AdStatus.AD_OPEN:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdOpen');
- Prompt.showToast({
- message: 'splash ad open',
- duration: 1000
- });
- break;
- case AdStatus.AD_CLICKED:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdClick');
- Prompt.showToast({
- message: 'splash ad click',
- duration: 1000
- });
- break;
- case AdStatus.AD_CLOSED:
- hilog.info(0x0000, 'testTag', '%{public}s', 'Status is onAdClose');
- Prompt.showToast({
- message: 'splash ad close',
- duration: 1000
- });
- router.replaceUrl({
- url: 'pages/Index',
- })
- break;
- }
- }
- }
- })
- .width('100%')
- .height('100%')
- }.width('100%').height('100%')
- }
- }
- export enum AdStatus {
- AD_OPEN = 'onAdOpen',
- AD_CLICKED = 'onAdClick',
- AD_CLOSED = 'onAdClose'
- }