• Home
Name Date Size #Lines LOC

..--

common/22-Mar-2025-1,216746

frameworks/js/napi/22-Mar-2025-5,1524,069

BUILD.gnD22-Mar-20251.2 KiB2926

LICENSED22-Mar-20259.9 KiB177150

README.mdD22-Mar-202514.4 KiB405343

README_zh.mdD22-Mar-202513.5 KiB380329

advertising.gniD22-Mar-20251.1 KiB2921

bundle.jsonD22-Mar-20251.1 KiB5150

README.md

1# Advertising Service Component
2
3## Introduction
4
5The advertising service enables you to implement ad access without SDK integration.
6
7## Directory Structure
8
9```
10/domain/advertising/advertising # Service code of the advertising service component
11├── common                             # Public References code
12├── frameworks                         # Framework code
13│   └── js                             # External JS API implementation
14│       └── napi                       # External native API implementation
15├── LICENSE                            # License file
16├── BUILD.gn                           # Build entry
17└── bundle.json                        # Component description file
18```
19
20### Concepts
21
22- SA
23
24  SA, short for SystemAbility, is a ipc entity that runs in the server process. After receiving an external request, SA processes the request and returns the processing result, thereby implementing service provisioning for external systems.
25
26
27## How to Use
28
29The advertising SA receives an ad request, processes the request, and forwards the request to the ad platform. The ad platform finds the best ad content and sends it to the SA for display.
30
31### Creating an Ad Platform
32
33The following steps walk you (application developer) through on how to create an ad platform and interact with the system.
34
351. Create a server component that implements the ServiceExtensionAbility.
36
37   This component is the entry for SA interaction.
38
39   ```javascript
40   export default class AdsCoreService extends ServiceExtensionAbility {
41     private descriptor = 'com.xxx.xxx';
42
43     onCreate(want) {
44       HiAdLog.i(TAG, `service onCreate`);
45       HGlobalVariableManager.set("hmscoreFramework", "coreServiceAbilityContext", this.context);
46     }
47
48     onRequest(want, startId) {
49       HiAdLog.i(TAG, `service onRequest`);
50     }
51
52     onConnect(want) {
53       HiAdLog.i(TAG, `service onConnect, want: ${JSON.stringify(want)}`);
54       return new AdsCoreServiceRpcObj(this.descriptor);
55     }
56
57     onDisconnect(want) {
58       HiAdLog.i(TAG, `service onDisconnect`);
59     }
60
61     onDestroy() {
62       HiAdLog.i(TAG, `service onDestory`);
63     }
64   }
65   ```
66
672. Create an RPC object, which will be returned by the ServiceExtensionAbility server component to the SA.
68
69   This RPC object is used to receive requests from the SA and send callback data to the SA.
70
71   ```javascript
72   import rpc from '@ohos.rpc';
73   import bundleManager from '@ohos.bundle.bundleManager';
74
75   /**
76    * RPC object returned by AdsCoreService to the caller, which is used by the caller to send data to AdsCoreService.
77    */
78   export default class AdsCoreServiceRpcObj extends rpc.RemoteObject {
79     constructor(descriptor) {
80       super(descriptor);
81     }
82
83     /**
84      * System API for receiving requests from the SA
85      *
86      * @param code Service request code sent by the peer end.
87      * @param data Object that carries the parameters called by the client. The parameters are called in the following sequence: Uid, RemoteObject, AdRequestParams, AdOptions, and custom collection data. The parameters must be read in the same sequence.
88      * @param reply MessageSequence object to which the result is written.
89      * @param options Whether the operation is synchronous or asynchronous.
90      * @returns
91      */
92     async onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, options: rpc.MessageOption) {
93       // code: 1, indicating an ad request.
94       console.info(`onRemoteMessageRequest, the code is: ${code}`);
95
96       try {
97         // 1. Read the ad request data in the specified data read sequence.
98         // Read the RPC remote object on the SA side.
99         const replyRpcObj: rpc.IRemoteObject = data.readRemoteObject();
100        const req = {
101          // Read ad request parameters. For details about the data structure, see AdRequestParams in the API document.
102          reqParams: data.readString(),
103          // Read ad configuration parameters. For details about the data structure, see AdOptions in the API document.
104          adOptions: data.readString(),
105          // Read custom collection data.
106          collectedData: data.readString(),
107        };
108        // 2. Request data validation.
109        // 3. Request ad processing.
110        // Return the ad data. For details, see advertising.Advertisement in the API document.
111        const ads: Array<advertising.Advertisement> = [];
112        // 4. Send a response to the SA.
113        const respData = rpc.MessageSequence.create();
114        /**
115         * The following service response codes are possible:
116         * CODE_SUCCESS = 200
117         * CODE_INVALID_PARAMETERS = 401
118         * CODE_INTERNAL_ERROR = 100001
119         * CODE_INIT_CONFIG_FAILURE = 100002
120         * CODE_LOAD_ADS_FAILURE = 100003
121         */
122        respData.writeInt(200);
123        respData.writeString(JSON.stringify(ads));
124        const reply = rpc.MessageSequence.create();
125        replyRpcObj.sendMessageRequest(code, respData, reply, new rpc.MessageOption(1))
126          .catch(e => {
127            console.error(`send message from kit to caller failed, error msg: ${e.message}`);
128          });
129        return true;
130       } catch (e) {
131         console.error(`handle rpc request failed, msg: ${e.message}`);
132         return false;
133       }
134     }
135   ```
136
1373. Configure application information.
138
139   Modify the **ad_service_config.json** file in **services/advertising_manager/resource**.
140
141   **providerBundleName**: bundle name of the application, which corresponds to **bundleName** in **app.json5** under **AppScope**.
142
143   **providerAbilityName**: name of the server component that implements the ServiceExtensionAbility. This component is used to interact with the SA. It is **AdsCoreService** in the preceding example.
144
145   **providerUIAbilityName**: name of the component that implements the UIAbility. This component is used to display full-screen ads.
146
147   **providerUEAAbilityName**: name of the component that implements the UIExtensionAbility. This component is used to display non-full-screen ads.
148
1494. Publish a full-screen ad.
150
151   You can use the common event capability provided by the system to send the interactive operations of the full-screen ad to the application.
152
153```javascript
154import commonEvent from '@ohos.commonEventManager';
155
156// Publish a common event.
157commonEvent.publish("event", (err) => {
158  if (err.code) {
159    console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
160  } else {
161    console.info("[CommonEvent]Publish")
162  }
163})
164```
165
166### Requesting an Ad
167
168To request an ad, you must create an **AdLoader** object and call its **loadAd** method to initiate the request. You also need to use the **AdLoadListener** callback function to listen for the ad loading status.
169
170```javascript
171import advertising from '@ohos.advertising';
172import common from '@ohos.app.ability.common';
173
174try {
175  const context = getContext(this) as common.UIAbilityContext;
176  const adRequestParam = {
177    adType: 3, // Ad type, for example, native ad.
178    adId: "test", // Ad slot ID.
179  };
180  const adOption = {
181    adContentClassification: 'A', // Set the maximum ad content rating.
182  };
183  // Listen for the ad loading status.
184  const adLoaderListener = {
185    // Called when an ad request fails.
186    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
187      console.info(`request ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
188    },
189    // Called when an ad request is successful.
190    onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
191      console.info(`request ad success!`);
192      // Save the requested ad content for display.
193      const ads = ads;
194    }
195  };
196  // Create an AdLoader object.
197  const adLoader = new advertising.AdLoader(context);
198  // Call the loadAd method.
199  console.info(`request ad!`);
200  adLoader.loadAd(adReqParams, adOptions, adLoaderListener);
201} catch (err) {
202  console.error(`load ad catch error: ${err.code} ${err.message}`);
203}
204```
205
206### Showing a Full-Screen Ad
207
2081. Subscribe to the event.
209
210   Subscribe to the com.company.pps.action.PPS_REWARD_STATUS_CHANGED event to listen for changes on the reward ad page and receive reward information. The subscription must be initiated each time before an ad is displayed.
211
212   After receiving the common event, use **reward_ad_status** and **reward_ad_data** as keys in the **parameters** parameter of [CommonEventData](https://docs.openharmony.cn/pages/v4.0/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md/) to obtain changes on the reward ad page and obtain reward information, respectively. You can use the **rewardType** and **rewardAmount** attributes to obtain the name of a reward and its quantity.
213
214   ```javascript
215   import commonEvent from '@ohos.commonEventManager';
216
217   const KEY_REWARD_DATA = "reward_ad_data";
218   const KEY_REWARD_STATUS = "reward_ad_status";
219
220   export class RewardAdStatusHandler {
221     // Used to save the created subscriber object for subsequent subscription and unsubscription.
222     private subscriber;
223
224     // Subscription method, which must be called each time before an ad is displayed.
225     public registerPPSReceiver(): void {
226       if (this.subscriber) {
227         this.unRegisterPPSReceiver();
228       }
229       // Subscriber information.
230       const subscribeInfo = {
231         events: ["com.company.pps.action.PPS_REWARD_STATUS_CHANGED"],
232       };
233       // Callback for subscriber creation.
234       commonEvent.createSubscriber(subscribeInfo, (err, commonEventSubscriber) => {
235         if (err) {
236           console.error(`createSubscriber error, ${JSON.stringify(err)}`);
237           return;
238         }
239         console.debug(`createSubscriber success`);
240         this.subscriber = commonEventSubscriber;
241         // Callback for common event subscription.
242         if (!this.subscriber) {
243           console.warn(`need create subscriber`);
244           return;
245         }
246         commonEvent.subscribe(this.subscriber, (err, commonEventData) => {
247           if (err) {
248             console.error(`subscribe error, ${JSON.stringify(err)}`);
249           } else {
250             // The subscriber receives the common event.
251             console.debug(`subscribe data, ${JSON.stringify(commonEventData)}`);
252             // Obtain the changes on the reward ad page.
253             const status: string = commonEventData.parameters[KEY_REWARD_STATUS];
254             switch (status) {
255               case AdStatus.AD_OPEN:
256                 console.info(`onAdOpen`);
257                 break;
258               case AdStatus.AD_CLICKED:
259                 console.info(`onAdClick`);
260                 break;
261               case AdStatus.AD_CLOSED:
262                 console.info(`onAdClose`);
263                 this.unRegisterPPSReceiver();
264                 break;
265               case AdStatus.AD_REWARDED:
266                 // Obtain reward information.
267                 const rewardData = commonEventData.parameters[KEY_REWARD_DATA];
268                 const rewardType = rewardData?.rewardType;
269                 const rewardAmount = rewardData?.rewardAmount;
270                 console.info(`onAdReward, rewardType: ${rewardType}, rewardAmount: ${rewardAmount}`);
271                 break;
272               case AdStatus.AD_VIDEO_START:
273                 console.info(`onAdVideoStart`);
274                 break;
275               case AdStatus.AD_COMPLETED:
276                 console.info(`onAdCompleted`);
277                 break;
278               default:
279                 break;
280             }
281           }
282         });
283       });
284     }
285
286     // Unsubscribe from the event.
287     public unRegisterPPSReceiver(): void {
288       commonEvent.unsubscribe(this.subscriber, (err) => {
289         if (err) {
290           console.error(`unsubscribe error, ${JSON.stringify(err)}`);
291         } else {
292           console.info(`unsubscribe success`);
293           this.subscriber = null;
294         }
295       });
296     }
297
298     // Ad page changes
299     enum AdStatus {
300       AD_OPEN = "onAdOpen",
301       AD_CLICKED = "onAdClick",
302       AD_CLOSED = "onAdClose",
303       AD_REWARDED = "onAdReward",
304       AD_VIDEO_START = "onVideoPlayBegin",
305       AD_COMPLETED = "onVideoPlayEnd",
306     }
307   }
308   ```
309
3102. Show an ad.
311
312   Call the **showAd** method to show an ad.
313
314```javascript
315import advertising from '@ohos.advertising';
316import common from '@ohos.app.ability.common';
317
318@Entry
319@Component
320export struct ShowAd {
321  private context = getContext(this) as common.UIAbilityContext;
322  // Requested ad content.
323  private ad: advertising.Advertisement = void 0;
324  // Ad display parameters.
325  private adDisplayOptions: advertising.AdDisplayOptions = {
326	  // Whether to mute the ad. By default, the ad is not muted.
327	  mute: false,
328	}
329
330  build() {
331	Column() {
332      Button ("Show Ad")
333		.backgroundColor('#d3d4d6')
334		.fontSize(20)
335		.fontColor('#000')
336		.fontWeight(FontWeight.Normal)
337		.align(Alignment.Center)
338		.type(ButtonType.Capsule)
339		.width('90%')
340		.height(40)
341		.margin({ top: 10, bottom: 5 })
342		.onClick(() => {
343	      try {
344			// Show a full-screen ad, such as a reward ad.
345			advertising.showAd(this.ad, this.adDisplayOptions, this.context);
346	      } catch (err) {
347			hilog.error(0x0000, 'testTag', 'show ad catch error: %{public}d %{public}s', err.code, err.message);
348	      }
349		});
350	}
351	.width('100%')
352	.height('100%')
353  }
354}
355```
356
357### Showing a Non-Full-Screen Ad
358
359Use the AdComponent component to show a non-full-screen ad.
360
361```javascript
362import advertising from '@ohos.advertising';
363import { AdComponent } from '@ohos.cloud.AdComponent';
364
365@Entry
366@Component
367export struct ShowAd {
368  // Requested ad content.
369  private ads: Array[advertising.Advertisement] = [];
370  // Ad display parameters.
371  private adDisplayOptions: advertising.AdDisplayOptions = {
372    // Whether to mute the ad. By default, the ad is not muted.
373    mute: false,
374  }
375
376  build() {
377    Column() {
378      // Show a non-full-screen ad, such as a native ad.
379      AdComponent({ ads: this.ads, displayOptions: this.adDisplayOptions,
380        interactionListener: {
381          // Ad status change callback.
382          onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
383            switch(status) {
384              case AdStatus.AD_OPEN:
385                console.info(`onAdOpen`);
386                break;
387              case AdStatus.AD_CLICKED:
388                console.info(`onAdClick`);
389                break;
390              case AdStatus.AD_CLOSED:
391                console.info(`onAdClose`);
392                break;
393            }
394          }
395		}
396	  })
397      .width('100%')
398      .height('100%')
399    }.width('100%').height('100%')
400  }
401}
402```
403
404## Repositories Involved
405

README_zh.md

1# 广告服务框架部件
2
3## 简介
4
5广告服务框架指导OEM厂商搭建广告平台,从而为媒体提供广告服务;同时指导媒体使用广告服务框架开放接口,无需集成SDK,轻松实现广告的接入。
6
7## 目录
8
9```
10/domain/advertising/advertising  # 广告服务框架部件业务代码
11├── common                             # 公共引用
12├── frameworks                         # 框架代码
13│   └── js                             # 外部接口实现
14│       └── napi                       # napi 外部接口实现
15├── interfaces                         # 接口文件
16├── LICENSE                            # 证书文件
17├── BUILD.gn                           # 编译入口
18└── bundle.json                        # 部件描述文件
19```
20
21## 使用说明
22
23广告服务框架用于接收来自媒体的广告请求,进行处理后将请求转发到广告平台,广告平台需要找到广告内容给广告服务框架响应,用于后续的广告内容展示。
24
25### 创建广告平台
26
27以OEM厂商为例,描述如何创建广告平台。
28
291. 创建AdsServiceExtensionAbility的服务端组件
30
31   该组件是与广告服务框架交互的入口。
32
33   ```javascript
34   import AdsServiceExtensionAbility from '@ohos.advertising.AdsServiceExtensionAbility';
35   import { RespCallback } from '@ohos.advertising.AdsServiceExtensionAbility';
36   import advertising from '@ohos.advertising';
37
38   /**
39    * AdsExtensionAbility继承AdsServiceExtensionAbility类,实现onLoadAd和onLoadAdWithMultiSlots方法,获取广告内容并向广告服务框架返回广告数据。
40    * 想要继承AdsServiceExtensionAbility类必须是系统应用,并申请ohos.permission.GET_BUNDLE_INFO_PRIVILEGED权限,
41    * 同时module.json5中对应的extensionAbility的type属性对应的值需要设置为adsService。
42    */
43   export default class AdsExtensionAbility extends AdsServiceExtensionAbility {
44     /**
45      * 请求广告接口,接受媒体单广告位广告请求
46      *
47      * @param adParam 媒体发送的单广告位广告请求参数
48      * @param adOptions 媒体发送的请求广告配置
49      * @param respCallback 广告请求结果回调方法
50      */
51     onLoadAd(adParam: advertising.AdRequestParms, adOptions: advertising.AdOptions, respCallback: RespCallback) {
52       // 返回的广告数据
53       const ads: Array<advertising.Advertisement> = [];
54       ads.push({adType: 7, uniqueId: '111111', rewardVerifyConfig: null, rewarded: false, clicked: false});
55       // 广告位ID
56       const slot: string = 'test1';
57       const resMap: Map<string, Array<advertising.Advertisement>> = new Map();
58       // 回调添加广告位对应的广告信息
59       respMap.set(slot, ads);
60       // 当resMap为空的时候,会触发广告请求失败
61       respCallback(respMap);
62     }
63
64     /**
65      * 请求广告接口,接受媒体多广告位广告请求
66      *
67      * @param adParam 媒体发送的多广告位广告请求参数
68      * @param adOptions 媒体发送的请求广告配置
69      * @param respCallback 广告请求结果回调方法
70      */
71     onLoadAdWithMultiSlots(adParams: advertising.AdRequestParms[], adOptions: advertising.AdOptions, respCallback: RespCallback) {
72       // 返回的广告数据
73       const ads1: Array<advertising.Advertisement> = [];
74       ads1.push({adType: 7, uniqueId: '111111', rewardVerifyConfig: null, rewarded: false, clicked: false});
75       ads1.push({adType: 7, uniqueId: '222222', rewardVerifyConfig: null, rewarded: false, clicked: false});
76       // 广告位ID
77       const slot1: string = 'test1';
78       // 返回的广告数据
79       const ads2: Array<advertising.Advertisement> = [];
80       ads2.push({adType: 7, uniqueId: '333333', rewardVerifyConfig: null, rewarded: false, clicked: false});
81       ads2.push({adType: 7, uniqueId: '444444', rewardVerifyConfig: null, rewarded: false, clicked: false});
82       // 广告位ID
83       const slot2: string = 'test2';
84       const resMap: Map<string, Array<advertising.Advertisement>> = new Map();
85       // 回调添加广告位对应的广告信息
86       respMap.set(slot1, ads1);
87       respMap.set(slot2, ads2);
88       // 当resMap为空的时候,会触发广告请求失败
89       respCallback(respMap);
90     }
91   }
92   ```
93
942. 配置应用信息
95
96   修改frameworks/js/napi/ads/resource/ad_service_config.json文件。
97
98   providerBundleName:应用包名。AppScope下app.json5中的bundleName。
99
100   providerAbilityName:实现了ServiceExtensionAbility的服务端组件名称,该组件用于和广告服务框架交互。如上示例中的AdsExtensionAbility。
101
102   providerUIAbilityName:实现了UIAbility的组件名称,该组件用于展示全屏广告。
103
104   providerUEAAbilityName:实现了UIExtensionAbility的组件名称,该组件用于展示非全屏广告。
105
1063. 全屏广告发布事件
107   通过系统提供的公共事件能力将全屏广告的互动操作发送到APP
108```javascript
109import commonEvent from '@ohos.commonEventManager';
110
111// 设置发布公共事件的通知
112const options: Record<string, Object> = {
113  'code': 1,
114  'parameters': {
115    // 广告页面变化状态
116    'reward_ad_status': 'onAdRewarded',
117    // 设置onAdRewarded状态对应的奖励信息
118    'reward_ad_data': {
119      rewardType: 'coin', // 奖励物品的名称
120      rewardAmount: 10 // 奖励物品的数量
121    }
122  }
123}
124
125// 发布公共事件,事件ID可自定义
126commonEvent.publish("com.company.pps.action.PPS_REWARD_STATUS_CHANGED", options, (err) => {
127  if (err.code) {
128    console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
129  } else {
130    console.info("[CommonEvent]Publish")
131  }
132})
133```
134
135### 请求广告
136
137以媒体为例,描述如何使用广告服务框架开放接口。
138
139请求广告需要创建一个AdLoader对象,通过AdLoader的loadAd方法请求广告。然后通过AdLoadListener回调来监听广告的加载状态。
140
141```javascript
142import advertising from '@ohos.advertising';
143import common from '@ohos.app.ability.common';
144
145try {
146  const context = getContext(this) as common.UIAbilityContext;
147  const adRequestParam = {
148    adType: 3, // 广告类型:如原生广告
149    adId: "test", // 测试广告位ID
150  };
151  const adOption = {
152    adContentClassification: 'A', //设置广告内容分级上限
153  };
154  // 广告请求回调监听
155  const adLoaderListener = {
156    // 广告请求失败回调
157    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
158      console.info(`request ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
159    },
160    // 广告请求成功回调
161    onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
162      console.info(`request ad success!`);
163      // 保存请求到的广告内容用于展示
164      const ads = ads;
165    }
166  };
167  // 创建AdLoader广告对象
168  const adLoader = new advertising.AdLoader(context);
169  // 调用广告请求接口
170  console.info(`request ad!`);
171  adLoader.loadAd(adReqParams, adOptions, adLoaderListener);
172} catch (err) {
173  console.error(`load ad catch error: ${err.code} ${err.message}`);
174}
175```
176
177### 展示全屏广告
178
179以媒体为例,描述如何使用广告服务框架开放接口。
180
1811. 事件订阅
182
183   开发者需要在App中订阅com.company.pps.action.PPS_REWARD_STATUS_CHANGED事件来监听激励广告页面变化并接收奖励信息。订阅需要在每次展示广告前调用 。
184
185   订阅者接收到公共事件后,可以从[CommonEventData](https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventData.md/)的parameters参数中使用"reward_ad_status"作为key值获取激励广告页面变化状态,使用"reward_ad_data"作为key值获取奖励信息,属性rewardType用来获取奖励物品的名称,rewardAmount用来获取奖励物品的数量。
186
187   ```javascript
188   import commonEvent from '@ohos.commonEventManager';
189
190   const KEY_REWARD_DATA = "reward_ad_data";
191   const KEY_REWARD_STATUS = "reward_ad_status";
192
193   export class RewardAdStatusHandler {
194     // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
195     private subscriber;
196
197     // 订阅方法,需要在每次展示广告前调用
198     public registerPPSReceiver(): void {
199       if (this.subscriber) {
200         this.unRegisterPPSReceiver();
201       }
202       // 订阅者信息
203       const subscribeInfo = {
204         events: ["com.company.pps.action.PPS_REWARD_STATUS_CHANGED"],
205       };
206       // 创建订阅者回调
207       commonEvent.createSubscriber(subscribeInfo, (err, commonEventSubscriber) => {
208         if (err) {
209           console.error(`createSubscriber error, ${JSON.stringify(err)}`);
210           return;
211         }
212         console.debug(`createSubscriber success`);
213         this.subscriber = commonEventSubscriber;
214         // 订阅公共事件回调
215         if (!this.subscriber) {
216           console.warn(`need create subscriber`);
217           return;
218         }
219         commonEvent.subscribe(this.subscriber, (err, commonEventData) => {
220           if (err) {
221             console.error(`subscribe error, ${JSON.stringify(err)}`);
222           } else {
223             // 订阅者成功接收到公共事件
224             console.debug(`subscribe data, ${JSON.stringify(commonEventData)}`);
225             // 获取激励广告页面变化状态
226             const status: string = commonEventData.parameters[KEY_REWARD_STATUS];
227             switch (status) {
228               case AdStatus.AD_OPEN:
229                 console.info(`onAdOpen`);
230                 break;
231               case AdStatus.AD_CLICKED:
232                 console.info(`onAdClick`);
233                 break;
234               case AdStatus.AD_CLOSED:
235                 console.info(`onAdClose`);
236                 this.unRegisterPPSReceiver();
237                 break;
238               case AdStatus.AD_REWARDED:
239                 // 获取奖励信息
240                 const rewardData = commonEventData.parameters[KEY_REWARD_DATA];
241                 const rewardType = rewardData?.rewardType;
242                 const rewardAmount = rewardData?.rewardAmount;
243                 console.info(`onAdReward, rewardType: ${rewardType}, rewardAmount: ${rewardAmount}`);
244                 break;
245               case AdStatus.AD_VIDEO_START:
246                 console.info(`onAdVideoStart`);
247                 break;
248               case AdStatus.AD_COMPLETED:
249                 console.info(`onAdCompleted`);
250                 break;
251               default:
252                 break;
253             }
254           }
255         });
256       });
257     }
258
259     // 取消订阅
260     public unRegisterPPSReceiver(): void {
261       commonEvent.unsubscribe(this.subscriber, (err) => {
262         if (err) {
263           console.error(`unsubscribe error, ${JSON.stringify(err)}`);
264         } else {
265           console.info(`unsubscribe success`);
266           this.subscriber = null;
267         }
268       });
269     }
270
271     // 广告页面变化状态
272     enum AdStatus {
273       AD_OPEN = "onAdOpen",
274       AD_CLICKED = "onAdClick",
275       AD_CLOSED = "onAdClose",
276       AD_REWARDED = "onAdReward",
277       AD_VIDEO_START = "onVideoPlayBegin",
278       AD_COMPLETED = "onVideoPlayEnd",
279     }
280   }
281   ```
282
2832. 展示广告
284
285   调用showAd方法来展示广告。
286
287```javascript
288import advertising from '@ohos.advertising';
289import common from '@ohos.app.ability.common';
290
291@Entry
292@Component
293export struct ShowAd {
294  private context = getContext(this) as common.UIAbilityContext;
295  // 请求到的广告内容
296  private ad: advertising.Advertisement = void 0;
297  // 广告展示参数
298  private adDisplayOptions: advertising.AdDisplayOptions = {
299	  // 是否静音,默认不静音
300	  mute: false,
301	}
302
303  build() {
304	Column() {
305      Button("展示广告")
306		.backgroundColor('#d3d4d6')
307		.fontSize(20)
308		.fontColor('#000')
309		.fontWeight(FontWeight.Normal)
310		.align(Alignment.Center)
311		.type(ButtonType.Capsule)
312		.width('90%')
313		.height(40)
314		.margin({ top: 10, bottom: 5 })
315		.onClick(() => {
316	      try {
317			// 展示全屏广告,如激励广告
318			advertising.showAd(this.ad, this.adDisplayOptions, this.context);
319	      } catch (err) {
320			hilog.error(0x0000, 'testTag', 'show ad catch error: %{public}d %{public}s', err.code, err.message);
321	      }
322		});
323	}
324	.width('100%')
325	.height('100%')
326  }
327}
328```
329
330### 展示非全屏广告
331
332以媒体为例,描述如何使用广告服务框架开放接口。
333
334在您的页面中使用AdComponent组件展示非全屏广告。
335
336```javascript
337import advertising from '@ohos.advertising';
338import { AdComponent } from '@ohos.cloud.AdComponent';
339
340@Entry
341@Component
342export struct ShowAd {
343  // 请求到的广告内容
344  private ads: Array[advertising.Advertisement] = [];
345  // 广告展示参数
346  private adDisplayOptions: advertising.AdDisplayOptions = {
347    // 是否静音,默认不静音
348    mute: false,
349  }
350
351  build() {
352    Column() {
353      // AdComponent组件用于展示非全屏广告,如原生广告
354      AdComponent({ ads: this.ads, displayOptions: this.adDisplayOptions,
355        interactionListener: {
356          // 广告状态变化回调
357          onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
358            switch(status) {
359              case AdStatus.AD_OPEN:
360                console.info(`onAdOpen`);
361                break;
362              case AdStatus.AD_CLICKED:
363                console.info(`onAdClick`);
364                break;
365              case AdStatus.AD_CLOSED:
366                console.info(`onAdClose`);
367                break;
368            }
369          }
370		}
371	  })
372      .width('100%')
373      .height('100%')
374    }.width('100%').height('100%')
375  }
376}
377```
378
379## 相关仓
380