如何展示一个banner广告

​如何展示一个banner广告

HarmonyOS
2024-08-07 09:26:18
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
koarla
import { advertising, AutoAdComponent, 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';

/**
 * Banner广告页面
 */
@Entry
@Component
export struct LoadAd {
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  // 广告展示参数
  private adDisplayOptions: advertising.AdDisplayOptions = {
    // 广告轮播的时间间隔,单位ms,取值范围[30000, 120000]
    refreshTime: 30000
  };
  // 广告配置
  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'
  };
  // Banner广告请求参数
  @State bannerAdReqParams: advertising.AdRequestParams = {
    adId: 'testw6vs28auh3',
    adType: AdType.BANNER_AD,
    adCount: 1,
    adWidth: 360,
    adHeight: 57
  };
  // Banner广告素材宽高比
  private ratio: number = 1;
  @State visibilityState: Visibility = Visibility.None;

  aboutToAppear() {
    try {
      // 请求用户授权
      this.requestOAIDTrackingConsentPermissions(this.context);
      this.initData();
    } catch (err) {
      hilog.error(0x0000, TAG, '%{public}s', `catch err, code: ${err.code}, message: ${err.message}`);
    }
    hilog.info(0x0000, TAG, '%{public}s', 'aboutToAppear');
  }

  build() {
    Stack({ alignContent: Alignment.Top }) {
      this.actionBar($r("app.string.banner_ads_demo_title"))
      Column() {
        this.customButton($r("app.string.request_banner_ad_btn"), () => {
          this.visibilityState = Visibility.Visible;
        })
      }.width('100%').height('80%').justifyContent(FlexAlign.Center)

      Stack({ alignContent: Alignment.Bottom }) {
        this.buildImageView();
        this.buildBannerView();
      }.visibility(this.visibilityState)
    }
    .width('100%')
    .height('100%')
  }

  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.bannerAdReqParams.oaid = data;
            hilog.info(0x0000, TAG, '%{public}s', `succeeded in getting adsIdentifierInfo by promise`);
          }).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}, message: ${err.message}`);
    }
  }

  private initData() {
    const adWidth: number = this.bannerAdReqParams.adWidth as number;
    const adHeight: number = this.bannerAdReqParams.adHeight as number;
    if (adWidth > 0 && adHeight > 0) {
      this.ratio = adWidth / adHeight;
    }
  }

  @Builder
  buildImageView() {
    Image($r('app.media.banner_background'))
      .objectFit(ImageFit.Cover)
      .onError(() => {
        hilog.error(0x0000, TAG, '%{public}s', 'buildImageView image load error');
      })
      .onComplete(() => {
        hilog.info(0x0000, TAG, '%{public}s', 'buildImageView image load complete');
      })
  }

  @Builder
  buildBannerView() {
    Row() {
      AutoAdComponent({
        adParam: this.bannerAdReqParams,
        adOptions: this.adOptions,
        displayOptions: this.adDisplayOptions,
        interactionListener: {
          onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
            hilog.info(0x0000, TAG, '%{public}s', `status is ${status}`);
            switch (status) {
              case AdStatus.AD_OPEN:
                hilog.info(0x0000, TAG, '%{public}s', 'onAdOpen');
                break;
              case AdStatus.AD_CLICKED:
                hilog.info(0x0000, TAG, '%{public}s', 'onAdClick');
                break;
              case AdStatus.AD_CLOSED:
                hilog.info(0x0000, TAG, '%{public}s', 'onAdClose');
                this.visibilityState = Visibility.None;
                break;
              case AdStatus.AD_LOAD:
                hilog.info(0x0000, TAG, '%{public}s', 'onAdLoad');
                break;
              case AdStatus.AD_FAIL:
                hilog.info(0x0000, TAG, '%{public}s', 'onAdFail');
                this.visibilityState = Visibility.None;
                break;
            }
          }
        }
      })
    }
    .width('100%')
    .aspectRatio(this.ratio)
    .padding({ bottom: 5 })
  }

  @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 {
  // Banner广告的类型
  BANNER_AD = 8
}

enum AdStatus {
  AD_LOAD = "onAdLoad",

  AD_FAIL = "onAdFail",

  AD_OPEN = "onAdOpen",

  AD_CLICKED = "onAdClick",

  AD_CLOSED = "onAdClose"
}
分享
微博
QQ
微信
回复
2024-08-07 11:36:26
相关问题
如何展示一个原生广告
263浏览 • 1回复 待解决
如何展示一个贴片广告
276浏览 • 1回复 待解决
如何展示一个激励广告
259浏览 • 1回复 待解决
如何展示一个开屏广告
340浏览 • 1回复 待解决
如何展示一个插屏广告
314浏览 • 1回复 待解决
如何展示一个半屏广告
354浏览 • 1回复 待解决
如何创建一个window?
229浏览 • 1回复 待解决
如何随机生成一个汉字?
246浏览 • 1回复 待解决
HarmonyOS 如何返回一个颜色?
162浏览 • 1回复 待解决
如何设置一个通知按钮
293浏览 • 1回复 待解决
如何实现一个折叠组件
844浏览 • 1回复 待解决
如何创建一个worker线程
810浏览 • 1回复 待解决
HarmonyOS 如何遍历一个JSON Object
261浏览 • 1回复 待解决