如何展示一个开屏广告

如何展示一个开屏广告

HarmonyOS
2024-08-07 09:29:42
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
一意孤行的
import { router, Prompt } from '@kit.ArkUI';
import { advertising, identifier } from '@kit.AdsKit';
import { common, abilityAccessCtrl } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG = 'Ads Demo-LoadAd';

/**
 * 流量变现服务演示页面
 */
@Entry
@Component
export struct LoadAd {
  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 = {
    adId: 'testd7c5cewoj6',
    adType: AdType.SPLASH_AD,
    adCount: 1
  }
  // 开屏图片广告请求参数
  private splashImageAdReqParams: advertising.AdRequestParams = {
    adId: 'testq6zq98hecj',
    adType: AdType.SPLASH_AD,
    adCount: 1
  }

  aboutToAppear() {
    try {
      // 使用Promise回调方式获取OAID
      this.requestOAIDTrackingConsentPermissions(this.context);
    } catch (error) {
      hilog.error(0x0000, TAG, '%{public}s', `catch err, code: ${error.code}, message: ${error.message}`);
    }
    hilog.info(0x0000, TAG, '%{public}s', 'aboutToAppear');
  }

  build() {
    Column() {
      this.actionBar($r("app.string.ads_demo_title"))
      Column() {
        // 跳转到开屏视频广告展示页面
        this.customButton(
          $r("app.string.request_splash_video_ad_btn"), () => {
          this.requestAd(this.splashVideoAdReqParams, this.adOptions);
        }
        );
        // 跳转到开屏图片广告展示页面
        this.customButton($r("app.string.request_splash_image_ad_btn"), () => {
          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 {
    // 给AdRequestParams设置oaid参数
    adReqParams.oaid = this.oaid;
    // 广告请求回调监听
    const adLoaderListener: advertising.AdLoadListener = {
      // 广告请求失败回调
      onAdLoadFailure: (errorCode: number, errorMsg: string) => {
        hilog.error(0x0000, TAG, '%{public}s', `request ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
        Prompt.showToast({
          message: 'request ad failed, code is: ' + errorCode + 'message is: ' + errorMsg,
          duration: 1000
        });
      },
      // 广告请求成功回调
      onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
        hilog.info(0x0000, TAG, '%{public}s', 'succeeded in requesting ad!');
        // 保存请求到的广告内容用于展示
        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.info(0x0000, TAG, '%{public}s', 'error adType');
          }
        }
      }
    };
    // 创建AdLoader广告对象
    const load: advertising.AdLoader = new advertising.AdLoader(this.context);
    // 调用广告请求接口
    hilog.info(0x0000, TAG, '%{public}s', 'request ad!');
    load.loadAd(adReqParams, adOptions, adLoaderListener);
  }

  private requestOAIDTrackingConsentPermissions(context: common.Context): void {
    // 进入页面时触发动态授权弹框,向用户请求授权广告跟踪权限
    const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    try {
      atManager.requestPermissionsFromUser(context, ["ohos.permission.APP_TRACKING_CONSENT"]).then((data) => {
        if (data.authResults[0] == 0) {
          hilog.info(0x0000, TAG, '%{public}s', 'succeeded in requesting permission');
          identifier.getOAID().then((data: string) => {
            this.oaid = data;
            hilog.info(0x0000, TAG, '%{public}s', `succeeded in getting adsIdentifierInfo by promise: ${this.oaid}`);
          }).catch((error: BusinessError) => {
            hilog.error(0x0000, TAG, '%{public}s', `getAdsIdentifierInfo failed, message: ${error.message}`);
          })
        } else {
          hilog.info(0x0000, TAG, '%{public}s', 'user rejected');
        }
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, TAG, '%{public}s', `request permission failed, error: ${err.code} ${err.message}`);
      })
    } catch (err) {
      hilog.error(0x0000, TAG, '%{public}s', `catch err, code: ${err.code}, msg: ${err.message}`);
    }
  }

  @Builder
  actionBar(title: Resource | string) {
    Row() {
      if (title) {
        Text(title)
          .fontSize(24)
          .fontColor(Color.White)
          .fontWeight(FontWeight.Medium)
          .margin({ left: 16 })
      }
    }
    .width('100%')
    .height('10%')
    .padding({
      top: 16,
      bottom: 16,
      left: 24,
      right: 24
    })
    .backgroundColor(Color.Black)
  }

  @Builder
  customButton(mText: string | Resource, mOnClick: (event?: ClickEvent) => void) {
    Column() {
      Button(mText)
        .backgroundColor('#d3d4d6')
        .fontSize(20)
        .fontColor('#000')
        .fontWeight(FontWeight.Normal)
        .align(Alignment.Center)
        .type(ButtonType.Capsule)
        .width('90%')
        .height(40)
        .margin({ top: 10, bottom: 5 })
        .onClick(mOnClick);
    }
  }
}

enum AdType {
  // 开屏广告的类型
  SPLASH_AD = 1
}

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, TAG, '%{public}s', `routePage  + ${pageUri}`);
    router.pushUrl(options);
  } catch (error) {
    hilog.error(0x0000, TAG, '%{public}s', `routePage fail callback, code: ${error.code}, msg: ${error.message}`);
  }
}
分享
微博
QQ
微信
回复
2024-08-07 11:41:19
相关问题
如何展示一个贴片广告
383浏览 • 1回复 待解决
如何展示一个原生广告
378浏览 • 1回复 待解决
如何展示一个插屏广告
522浏览 • 1回复 待解决
如何展示一个激励广告
368浏览 • 1回复 待解决
如何展示一个banner广告
431浏览 • 1回复 待解决
如何展示一个半屏广告
533浏览 • 1回复 待解决
当前HarmonyOS是否有开屏广告的能力
473浏览 • 1回复 待解决
如何创建一个window?
334浏览 • 1回复 待解决
如何创建一个worker线程
927浏览 • 1回复 待解决
如何实现一个折叠组件
998浏览 • 1回复 待解决
如何设置一个通知按钮
390浏览 • 1回复 待解决
HarmonyOS 如何返回一个颜色?
290浏览 • 1回复 待解决
如何随机生成一个汉字?
361浏览 • 1回复 待解决