• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.advertising (Ads Service Framework)
2
3
4The advertising module provides APIs for requesting and displaying ads.
5
6
7> **NOTE**
8>
9> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
10
11
12## Modules to Import
13
14```ts
15import advertising from '@ohos.advertising';
16```
17
18
19## constructor
20
21constructor(context?: common.Context);
22
23Constructor.
24
25**System capability**: SystemCapability.Advertising.Ads
26
27**Since**: 11
28
29**Parameters**
30
31| Name| Type| Mandatory| Description|
32| -------- | -------- | -------- | -------- |
33| context | common.[Context](js-apis-inner-application-context.md) | No| Context of the ability or application.|
34
35**Example**
36
37For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
38
39```ts
40import advertising from '@ohos.advertising';
41import common from '@ohos.app.ability.common';
42
43function createConstructor(context: common.Context): void {
44  const load: advertising.AdLoader = new advertising.AdLoader(context);
45}
46```
47
48
49## advertising.loadAd
50
51loadAd(adParam: advertising.AdRequestParams, adOptions: advertising.AdOptions, listener: advertising.AdLoadListener): void
52
53Loads an ad.
54
55**System capability**: SystemCapability.Advertising.Ads
56
57**Since**: 11
58
59**Parameters**
60
61| Name| Type| Mandatory| Description|
62| -------- | -------- | -------- | -------- |
63| adParam | advertising.[AdRequestParams](#adrequestparams) | Yes| Ad request parameters.|
64| adOptions | advertising.[AdOptions](#adoptions) | Yes| Ad configuration.|
65| listener | advertising.[AdLoadListener](#adloadlistener) | Yes| Ad request callback.|
66
67**Error codes**
68
69For details about the following error codes, see [Ads Service Framework Error Codes](../errorcodes/errorcode-ads.md).
70
71| ID| Error Message|
72| -------- | -------- |
73| 21800001 | System internal error. |
74| 21800003 | Failed to load the ad request. |
75
76**Example**
77
78For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
79
80```ts
81import advertising from '@ohos.advertising';
82import common from '@ohos.app.ability.common';
83import hilog from '@ohos.hilog';
84
85function requestAd(context: common.Context): void {
86  const adRequestParam: advertising.AdRequestParams = {
87    // Ad type.
88    adType: 3,
89    // Ad ID.
90    adId: "test1",
91  };
92  const adOptions: advertising.AdOptions = {
93    // Set the maximum ad content rating.
94    adContentClassification: 'A',
95  };
96  // Listener for the ad loading status.
97  const adLoaderListener: advertising.AdLoadListener = {
98    // Called when the ad request fails.
99    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
100      hilog.error(0x0000, 'testTag', '%{public}s', `request single ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
101    },
102    // Called when the ad request is successful.
103    onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
104      hilog.info(0x0000, 'testTag', '%{public}s', 'request single ad success!');
105      // Save the requested ad content for display.
106      const returnAds = ads;
107    }
108  };
109  // Create an AdLoader object.
110  const load: advertising.AdLoader = new advertising.AdLoader(context);
111  // Load the ad.
112  hilog.info(0x0000, 'testTag', '%{public}s', 'request single ad!');
113  load.loadAd(adRequestParam, adOptions, adLoaderListener);
114}
115```
116
117
118## advertising.loadAdWithMultiSlots
119
120loadAdWithMultiSlots(adParams: advertising.AdRequestParams[], adOptions: advertising.AdOptions, listener: advertising.MultiSlotsAdLoadListener): void
121
122Loads multiple ads.
123
124**System capability**: SystemCapability.Advertising.Ads
125
126**Since**: 11
127
128**Parameters**
129
130| Name| Type| Mandatory| Description|
131| -------- | -------- | -------- | -------- |
132| adParams | advertising.[AdRequestParams](#adrequestparams)[] | Yes| Ad request parameters.|
133| adOptions | advertising.[AdOptions](#adoptions) | Yes| Ad configuration.|
134| listener | advertising.[MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes| Ad request callback.|
135
136**Error codes**
137
138For details about the following error codes, see [Ads Service Framework Error Codes](../errorcodes/errorcode-ads.md).
139
140| ID| Error Message|
141| -------- | -------- |
142| 21800001 | System internal error. |
143| 21800003 | Failed to load the ad request. |
144
145**Example**
146
147For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
148
149```ts
150import advertising from '@ohos.advertising';
151import common from '@ohos.app.ability.common';
152import hilog from '@ohos.hilog';
153
154function requestMultiAd(context: common.Context): void {
155  const adRequestParamArray: advertising.AdRequestParams[] = [{
156      // Ad type.
157      adType: 3,
158      // Ad ID.
159      adId: "test1",
160    } as advertising.AdRequestParams,
161    {
162      // Ad type.
163      adType: 3,
164      // Ad ID.
165      adId: "test2",
166    } as advertising.AdRequestParams
167  ];
168  const adOptions: advertising.AdOptions = {
169    // Set the maximum ad content rating.
170    adContentClassification: 'A',
171  };
172  // Listener for the ad loading status.
173  const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = {
174    // Called when the ad request fails.
175    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
176      hilog.error(0x0000, 'testTag', '%{public}s', `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
177    },
178    // Called when the ad request is successful.
179    onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => {
180      hilog.info(0x0000, 'testTag', '%{public}s', 'request multi ads success!');
181      // Save the requested ad content for display.
182      let returnAds: Array<advertising.Advertisement> = [];
183      ads.forEach((adsArray) => returnAds.push(...adsArray));
184    }
185  };
186  // Create an AdLoader object.
187  const load: advertising.AdLoader = new advertising.AdLoader(context);
188  // Load the ad.
189  hilog.info(0x0000, 'testTag', '%{public}s', 'request multi ads!');
190  load.loadAdWithMultiSlots(adRequestParamArray, adOptions, multiSlotsAdLoaderListener);
191}
192```
193
194
195## advertising.showAd
196
197showAd(ad: advertising.Advertisement, options: advertising.AdDisplayOptions, context?: common.UIAbilityContext): void
198
199Shows a full-screen ad.
200
201**System capability**: SystemCapability.Advertising.Ads
202
203**Since**: 11
204
205**Parameters**
206
207
208| Name| Type| Mandatory| Description|
209| -------- | -------- | -------- | -------- |
210| ad | advertising.[Advertisement](#advertisement) | Yes| Ad object.|
211| options | advertising.[AdDisplayOptions](#addisplayoptions) | Yes| Ad display parameters.|
212| context | common.[UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No| UIAbility context.|
213
214
215**Error codes**
216
217
218For details about the following error codes, see [Ads Service Framework Error Codes](../errorcodes/errorcode-ads.md).
219
220
221| ID| Error Message|
222| -------- | -------- |
223| 21800001 | System internal error. |
224| 21800004 | Failed to display the ad. |
225
226
227**Example**
228
229```ts
230import advertising from '@ohos.advertising';
231import hilog from '@ohos.hilog';
232import common from '@ohos.app.ability.common';
233
234@Component
235export struct ShowAd {
236  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
237  // Requested ad content.
238  private ad?: advertising.Advertisement;
239  // Ad display parameters.
240  private adDisplayOptions: advertising.AdDisplayOptions = {
241    // Whether to mute the ad. By default, the ad is not muted.
242    mute: false,
243  }
244
245  build() {
246    Column() {
247        Button ('Show Ad')
248          .onClick(() => {
249            try {
250              // Show the ad.
251              advertising.showAd(this.ad, this.adDisplayOptions, this.context);
252            } catch (err) {
253              hilog.error(0x0000, 'testTag', '%{public}s', `show ad catch error: ${err.code} ${err.message}`);
254            }
255          });
256    }
257    .width('100%')
258    .height('100%')
259  }
260}
261```
262
263
264## AdOptions
265
266Defines the ad configuration.
267
268**System capability**: SystemCapability.Advertising.Ads
269
270
271| Name| Type| Mandatory| Description|
272| -------- | -------- | -------- | -------- |
273| tagForChildProtection | number | No| Whether to process the ad request according to the Children's Online Privacy Protection Act (COPPA).<br>- **-1**: You do not want to specify whether the ad content needs to be COPPA-compliant.<br>- **0**: The ad content does not need to be COPPA-compliant.<br>- **1**: The ad content must be COPPA-compliant (no ad will be returned for this ad request).|
274| adContentClassification | string | No| Maximum ad content rating.<br>- **W**: content suitable for toddlers and older audiences.<br>- **PI**: content suitable for kids and older audiences.<br>- **J**: content suitable for teenagers and older audiences.<br>- **A**: content only suitable for adults.|
275| nonPersonalizedAd | number | No| Whether to request non-personalized ads.<br>- **0**: request for personalized and non-personalized ads.<br>- **1**: request for non-personalized ads.|
276| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.<br> - **totalDuration**: The value is of the number type, in seconds. This parameter is mandatory for roll ads and is used to set the total duration of roll ads.<br> - **placementAdCountDownDesc**: The value is of the string type. This parameter is optional for roll ads and is used to set the countdown description of roll ads. This parameter must be encoded using the **encodeURI()** API. If this parameter is set, the countdown description is displayed. Otherwise, only the countdown is displayed.|
277
278
279## AdRequestParams
280
281Defines the ad request parameters.
282
283**System capability**: SystemCapability.Advertising.Ads
284
285
286| Name| Type| Mandatory| Description|
287| -------- | -------- | -------- | -------- |
288| adId | string | Yes| Ad ID|
289| adType | number | No| Type of the requested ad.<br>- **1**: splash ad.<br>- **3**: native ad.<br>- **7**: rewarded ad.<br>- **8**: banner ad.<br>- **12**: interstitial ad.<br>- **60**: roll ad.|
290| adCount | number | No| Number of ads requested.|
291| adWidth | number | No| Ad width.|
292| adHeight | number | No| Ad height.|
293| adSearchKeyword | string | No| Ad keyword.|
294| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.|
295
296
297## AdLoadListener
298
299Enumerates the callbacks used for the request for loading an ad.
300
301**System capability**: SystemCapability.Advertising.Ads
302
303
304| Name| Type| Mandatory| Description|
305| -------- | -------- | -------- | -------- |
306| onAdLoadFailure | function(errorCode: number, errorMsg: string): void | Yes| Called when the ad request fails.|
307| onAdLoadSuccess | function(ads: Array&lt;advertising.[Advertisement](#advertisement)&gt;): void | Yes| Called when the ad request is successful.|
308
309
310## MultiSlotsAdLoadListener
311
312Enumerates the callbacks used for the request for loading multiple ads.
313
314**System capability**: SystemCapability.Advertising.Ads
315
316
317| Name| Type| Mandatory| Description|
318| -------- | -------- | -------- | -------- |
319| onAdLoadFailure | function(errorCode: number, errorMsg: string): void | Yes| Called when the ad request fails.|
320| onAdLoadSuccess | function(adsMap: Map&lt;string, Array&lt;advertising.[Advertisement](#advertisement)&gt;&gt;): void | Yes| Called when the ad request is successful.|
321
322
323## Advertisement
324
325
326Defines the requested ad content.
327
328
329**System capability**: SystemCapability.Advertising.Ads
330
331
332| Name| Type| Mandatory| Description|
333| -------- | -------- | -------- | -------- |
334| adType | number | Yes| Ad type.|
335| uniqueId | string | Yes| Unique ID of the ad.|
336| rewarded | boolean | No| Whether users get rewarded for watching or clicking the ad.<br>- **true**: Users get rewarded.<br>- **false**: Users do not get rewarded. |
337| shown | boolean | No| Whether the ad is shown.<br>- **true**: The ad is shown.<br>- **false**: The ad is not shown.|
338| clicked | boolean | No| Whether the ad is clicked.<br>- **true**: The ad is clicked.<br>- **false**: The ad is not clicked.|
339| rewardVerifyConfig | Map&lt;string, string&gt; | No| Server verification parameter.<br>{<br>customData: "test",<br>userId: "12345"<br>} |
340| [key: string] | Object | No| Custom parameter.<br>- **isFullScreen**: The value is of the Boolean type. This parameter is used for splash ads to specify whether such an ad is in full-screen mode. The value **true** means that the ad is in full-screen mode, and **false** means that the ad is in half-screen mode.|
341
342
343## AdDisplayOptions
344
345
346Defines the ad display parameters.
347
348
349**System capability**: SystemCapability.Advertising.Ads
350
351
352| Name| Type| Mandatory| Description|
353| -------- | -------- | -------- | -------- |
354| customData | string | No| Custom media data. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing.|
355| userId | string | No| User ID. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing.|
356| useMobileDataReminder | boolean | No| Whether to display a dialog box to notify users when they use mobile data to play videos or download applications.<br>- **true**: A dialog box is displayed.<br>- **false**: No dialog box is displayed.|
357| mute | boolean | No| Whether to mute the ad video.<br>- **true**: The ad video is muted.<br>- **false**: The ad video is not muted.|
358| audioFocusType | number | No| Type of the scenario where the audio focus is obtained during video playback.<br>- **0**: The focus is obtained when the video is played in mute or non-mute mode.<br>- **1**: The focus is not obtained when the video is played in mute mode.<br>- **2**: The focus is not obtained when the video is played in mute or non-mute mode. |
359| [key: string] | number \| boolean \| string \| undefined | No| Custom parameter.<br>- **refreshTime**: The value is of the number type, in ms. The value is in the range [30000, 120000]. This parameter is optional for the AutoAdComponent module and specifies the interval at which the ads rotate. If this parameter is set, ads are rotated at the interval specified by this parameter. Otherwise, ads are not rotated and only the first ad in the ad response is displayed.|
360
361
362## AdInteractionListener
363
364
365Defines the ad status change callback.
366
367**System capability**: SystemCapability.Advertising.Ads
368
369
370| Name| Type| Mandatory| Description|
371| -------- | -------- | -------- | -------- |
372| onStatusChanged | function(status: string, ad: advertising.[Advertisement](#advertisement), data: string): void | Yes| Ad display callback.<br>1. **status**: ad display status, which can be<br>**onAdOpen**, **onAdClose**, **onAdReward**, **onAdClick**, **onVideoPlayBegin**, or **onVideoPlayEnd**.<br>2. **ad**: content of the ad.<br>3. **data**: additional information. |
373