Integration Guide
Introduction
This document is intended for developers integrating the MG Ads SDK, describing how to correctly integrate various ad formats.
⚠️ Important:Before calling any ad functionality, you must complete both the CMP interface and the SDK initialization interface calls in order. Both are indispensable. For details, please refer to the "CMP and SDK Initialization Integration Guide".
MG Ads supports the following ad formats:
| No. | Ad Format | Default Size | Supported media Type |
|---|---|---|---|
| 1 | Full-screen Ad | 1920×1080 | image, web, video |
| 2 | Exit Ad | - | - |
| 3 | Banner Ad | 728×90 | image, web |
| 4 | Interstitial Ad | 1024×768 | image, web, video |
| 5 | Couplet Ad | 300×600 | image, web |
| 6 | Rewarded Ad | 1024×768 | web, video |
| 7 | Feed | - | image, web, video |
| 8 | Embedded Ad | - | image、web、video |
Ad Call Flow
App Launch
↓
Call SetAppId()
↓
Call OpenCmp()
↓
Wait for user to make selection
↓
Call Initialize()
↓
SDK initialization complete
↓
Call ad interface
↓
Ad displayed
⚠️ Mandatory Requirement: All ad interfaces must be called after Initialize() has successfully completed.
Pre-Integration Preparation
Step 1: Import Namespace
hDLL = LoadLibrary(L"MgAdSDKCSharpDLL.dll");
Step 2: Complete CMP and SDK Initialization
Please refer to the "CMP and SDK Initialization Integration Guide" to ensure the following are completed:
-
OpenCmp()
-
Initialize()
Step 3: Create Ad Unit
Log in to the MG Ads Developer Backend to create an ad unit and obtain the Ad Unit ID.
Developers can refer to the ad unit creation instructions in the MG Ads Developer Documentation: MG Ads - Developer Documentation Center | Complete SDK Integration Guide and API Reference | MG Ads
Step 4: Call Ad Interfaces
Select the corresponding ad format based on your business scenario:
| Usage Scenario | Recommended Ad Format |
|---|---|
| Game launch screen | Full-screen Ad |
| Game pause screen | Interstitial Ad |
| Game main interface | Banner Ad |
| Game settlement screen | Rewarded Ad |
| Game exit | Exit Ad |
| Custom UI area | Feed or Embedded Ad |
Ad Material Type Description
Each ad type supports specifying the material type via the media parameter. This parameter is optional; if left empty, a random ad creative type enabled in the MG backend will be returned. Available values are:
| media Value | Description | Ad Source |
|---|---|---|
image | Image ad, supported by default | MG |
web | Web ad, not open by default. To use, please contact the MG Product Manager to request permission after creating the ad unit. | |
video | Video ad, supported by default (some ad formats) | MG |
⚠️ Important: Web ads (MediaType set to
"web") are not open by default. To use them, please contact the MG Product Manager to request permission after creating the ad unit.
Step 5: Handle Ad Result
The results of the call are returned via an asynchronous callback event.
Ad Integration
Full-screen Ad
Description: Full-screen ads cover the entire application interface, suitable for game launch screens, scene transition screens, before level start, etc.
void ShowAd(const char* jsonParam)
Json Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For full-screen ads, please use 1 |
| handle | int | Required | Ad Container Handle |
| parentWidth | int | Required | Width of the ad container |
| parentHeight | int | Required | Height of the ad container |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
const char* FullScreenAdUnitId = "b871f83c5e8845f1b43325561bcdd6c7";
const char* ExitAdUnitId = "5076eab6ae1042b6b92f73ea01981475";
const char* BannerUnitId = "cb7d9688a2d9499992febb6b642b3625";
const char* InterstitialUnitId = "2cb66a1301404561881a3f26b6ce5ba7";
const char* CoupletUnitId = "b502f6e6281c43e4b28ea22503471039";
const char* RewardedUnitId = "2ae60936ba664fbfb7d92ce3a19c2915";
const char* FeedUnitId = "f152f6caf7a8440f8510bc31534baf4e";
const char* EmbeddedUnitId = "4192966a9db343f48dd2f6308ea9ec30";
//Calling the SDK's ad API
void showAd(const char* json) {
try
{
// Ensure that COM has been initialized before the call
if (!g_comInitialized) {
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr)) {
g_comInitialized = true;
}
}
ShowAd func = (ShowAd)GetProcAddress(hDLL, "ShowAd");
if (func) {
func(json);
}
}
catch (...)
{
}
}
//Full-screen ad
case ID_BTN_AD1:
{
CreateSplashScreenAdPanel(g_hwndMain);//Create a Full-Screen Ad Container
RECT clientRect;
if (GetClientRect(hWnd, &clientRect)) {
int clientWidth = clientRect.right - clientRect.left;
int clientHeight = clientRect.bottom - clientRect.top;
nlohmann::json json_obj = {
{"unitId", FullScreenAdUnitId},
{"appType", 1},
//{"media", "web"},
{"adType", 1},
{"handle", reinterpret_cast<int>(g_hwndMain)},
{"parentWidth", clientWidth},
{"parentHeight", clientHeight}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
}
break;
}
Banner Ad
Description: Banner ads are typically fixed at the bottom, suitable for game main interfaces, etc.
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For banner ads, please use 3 |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
case ID_BTN_AD3:
{
CreateBannerAdPanel(hWnd);
int containerHandle = reinterpret_cast<int>(g_hPnlBanner);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", BannerUnitId},
{"adType", 3},//Banner
{"handle", containerHandle}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
Interstitial Ad
Description: Interstitial ads pop up during application flow nodes, suitable for level end, page transitions, game pause, etc.
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Interstitial ads, please use 4 |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
case ID_BTN_AD4:
{
CreateInterstitialAdPannel(hWnd);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", InterstitialUnitId},
{"adType", 4},//Interstitial
{"handle", reinterpret_cast<int>(g_hPnlInterstitial)}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
Couplet Ad
Description: Couplet ads are fixed on the left and right sides of the interface, suitable for PC web games and similar scenarios.
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Couplet ads, please use 5 |
| handle | int | Required | Ad Container Handle |
| handle2 | int | Required | The handle for the right-side ad container |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
case ID_BTN_AD5:
{
CreateCoupletAdPannel(hWnd);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", CoupletUnitId},
{"adType", 5},//Couplet
{"handle", reinterpret_cast<int>(g_hPnlCoupletLeft)},
{"handle2", reinterpret_cast<int>(g_hPnlCoupletRight)}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
Rewarded Ad
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Rewarded ads, please use 6 |
| width | int | Required | Width of the ad container |
| height | int | Required | Height of the ad container |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
| comment | string | Optional | Developer-defined parameters (must be URL-encoded) |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Reward Granting Flow
plaintext
┌─────────────────┐
│ Call ShowAd() │
│ (pass rewarded ad params) │
└────────┬────────┘
↓
┌─────────────────┐
│ User watches ad │
└────────┬────────┘
↓
┌─────────────────────────────────────────┐
│ Ad playback complete, callback returns Json data │
└────────┬────────────────────────────────┘
↓
┌─────────────────┐ ┌─────────────────┐
│ completeStatus=1 │ │ completeStatus=0│
│ (full watch) │ │ (incomplete watch) │
└────────┬────────┘ └────────┬────────┘
↓ ↓
┌─────────────────┐ ┌─────────────────┐
│ Grant in-game reward │ │ Do not grant reward │
└────────┬────────┘ └─────────────────┘
↓
┌─────────────────────────────┐
│ Call ReportAdRewardFulfillment() │
│ Notify MG backend to verify │
└─────────────────────────────┘
Complete Code Example
// Call the ad interface on the UI thread
case ID_BTN_AD6:
{
CreateRewardAdPannel(hWnd);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", RewardedUnitId},
{"comment", "abc123"}, // Pass-through parameter; the front end must perform URL encoding; this parameter will be returned as-is in the ad close callback event.
{"adType", 6},
{"handle", reinterpret_cast<int>(g_hPnlReward)},
{"width", 1024},
{"height", 768}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
void onAdCloseEvent(char* s) {
AppendLog(L"onAdCloseEvent: %hs", s);
//...
// Destroy the ad container on the UI thread
try
{
nlohmann::json json_obj = nlohmann::json::parse(s);
std::string unitId = json_obj["unitId"];
if (unitId == RewardedUnitId)
{//Rewarded
DestroyWindow(g_hPnlReward);
g_hPnlReward = NULL;
int completeStatus = json_obj["completeStatus"];
if (completeStatus == 1)
{
std::string resourceId = json_obj["resourceId"];
std::string materialId = json_obj["materialId"];
std::string rewardId = json_obj["rewardId"];
// The ad has finished playing; the reward can be distributed
//...
// Report to MG
reportAdRewardFulfillment(unitId.c_str(), resourceId.c_str(), materialId.c_str(), rewardId.c_str());
AppendLog(L"reportAdRewardFulfillment Async: %hs", rewardId.c_str());
}
}
}
catch (...)
{
}
}
💡 Tips:
-
For rewarded video ads, the ad close callback must use
completeStatusto determine whether to award a reward, to prevent rewards from being issued before the ad has been fully viewed. -
The Comment field can be used to pass in-game parameters (e.g., reward type, amount). Be sure to URL-encode it when passing and decode it before use.
-
After successfully granting the reward, call ReportAdRewardFulfillment to notify the MG backend to complete verification.
Feed Ad
Description: Feed ads allow developers to specify an ad container, suitable for native ad feeds, in-list ads, etc. Developers need to define a container control (such as a Panel) in the Form in advance, and then pass that container to the SDK.
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Feed ads, please use 7 |
| width | int | Required | Width of the ad container |
| height | int | Required | Height of the ad container |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
case ID_BTN_AD7:
{
int containerHandle = reinterpret_cast<int>(g_hPnlFeed);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", FeedUnitId},
{"adType", 7},
{"width", 400},//Feed requires passing in the container's width and height.
{"height", 50},
{"handle", containerHandle}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
Embedded Ad
Description:Embedded ads allow developers to specify an ad container,For ads embedded within a page, custom UI area ad display, etc. Developers need to define a container control (such as a Panel) in the Form in advance, and then pass that container to the SDK.
void ShowAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Embedded Ad ads, please use 8 |
| width | int | Required | Width of the ad container |
| height | int | Required | Height of the ad container |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example
case ID_BTN_AD8:
{
int containerHandle = reinterpret_cast<int>(g_hPnlEmbedded);
nlohmann::json json_obj = {
{"appType", 1},
{"unitId", EmbeddedUnitId},
{"adType", 8},
{"width", 200},//Embedded requires passing in the container's width and height.
{"height", 200},
{"handle", containerHandle}
};
std::string jsonStr = json_obj.dump();
showAd(jsonStr.c_str());
break;
}
Exit Ad
Description: Exit-screen ads are triggered when exiting the game. To ensure a high ad display rate upon exiting the game, MG implements exit-screen ads in two steps:
-
After initialization is complete, load the exit-screen ad information into memory.
-
When exiting the game, directly display the exit-screen ad.
void SetupExitAd(const char* exitAdUnitId)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
Complete Code Example
// exit ad
// Step 1. After initialization is successful, load the exit ad resource
void onInitCompleteEvent(char* s) {
try
{
nlohmann::json json_obj = nlohmann::json::parse(s); //{"success":true,"data":""}
bool success = json_obj["success"];
if (success) {
AppendLog(L"Initialization successful");
if (auto func = (SetupExitAd)GetProcAddress(hdll, "SetupExitAd")) {
func(ExitAdUnitId); // load the exit ad resource
}
}
}
catch (...)
{
}
}
// exit ad
// Step 2. Display the exit ad when the application closes
case ID_BTN_EXITAD:
{
if (auto func = (ShowExitAdBlocking)GetProcAddress(hdll, "ShowExitAdBlocking")) {
func();
AppendLog(L"show fallback screen advert");
}
break;
}
Ad Close Event
Note: The callback event for ad closure is typically registered in the page's constructor.
Event Return Parameter Description
| Parameter Name | Parameter Description | Example |
|---|---|---|
| unitId | Ad unit ID provided by the developer | e333abaf22404c4a8d382c1e7ba42076 |
| advertStatus | Ad unit status | 1: Ad is playing normally; 2: Ad was closed by the backend; 3: No ad creative |
| The following parameters are specific to rewarded video ads | ||
| completeStatus | Ad playback status | 1: Ad has finished playing; rewards can be issued; 0: Ad has not finished playing |
| comment | Pass-through parameter provided by the developer, URL-encoded | abc%2c123 |
| rewardId | MG order number for the reward; used when the game reports redemption to MG after issuing the reward | String |
| resourceId | Resource ID | String |
| materialId | Ad creative ID | String |
Complete Sample Code
// App Launch
void InitMgAdSdk(HWND hWnd) {
if (hDLL) return;
hDLL = LoadLibrary(L"MgAdSDKCSharpDLL.dll");
if (hDLL) {
// Ad close callback event
if (auto func = (AdCloseEvent)GetProcAddress(hDLL, "AdCloseEvent"))
func(onAdCloseEvent);
// Ad preload callback event
if (auto func = (AdPreloadEvent)GetProcAddress(hDLL, "AdPreloadEvent"))
func(onAdPreloadEvent);
// Preload playback callback event; use as needed
if (auto func = (AdShowPreloadEvent)GetProcAddress(hDLL, "AdShowPreloadEvent"))
func(onAdShowPreloadEvent);
//...
}
}
void onAdCloseEvent(char* s) {
AppendLog(L"onAdCloseEvent: %hs", s);
//...
// Destroy the ad container on the UI thread
try
{
nlohmann::json json_obj = nlohmann::json::parse(s);
std::string unitId = json_obj["unitId"];
if (unitId == FullScreenAdUnitId)
{//Destroy the ad container on the UI thread
DestroyWindow(g_hPnlSplashScreen);
g_hPnlSplashScreen = NULL;
}
else if (unitId == RewardedUnitId)
{// Rewarded
DestroyWindow(g_hPnlReward);
g_hPnlReward = NULL;
int completeStatus = json_obj["completeStatus"];
if (completeStatus == 1)
{
std::string resourceId = json_obj["resourceId"];
std::string materialId = json_obj["materialId"];
std::string rewardId = json_obj["rewardId"];
// The ad has finished playing; the reward can be issued
//...
// Report to MG
reportAdRewardFulfillment(unitId.c_str(), resourceId.c_str(), materialId.c_str(), rewardId.c_str());
AppendLog(L"reportAdRewardFulfillment Async: %hs", rewardId.c_str());
}
}
}
catch (...)
{
}
}
Ad Preload Feature
⚠️ Applicable Scenario Description: The preload feature is only intended for developers who have integrated multiple ad platforms (e.g., integrating AppLovin, Vungle, YLH, MG, etc. simultaneously). If only integrating the MG Ads single platform, it is recommended to directly use ShowAd() without using the preload mode.
The preload feature provides two separate interfaces to help you prepare ad materials in advance before displaying ads, improving display success rates.
-
Preload Interface (PreloadAd): Requests and caches ad materials in advance.
-
Show Preloaded Ad Interface (ShowPreloadAd): Displays a successfully preloaded ad.
💡 Tip: The preload feature is available for all ad formats. You can call the preload interface before you need to display an ad, and then display it via the show interface once the ad is ready.
Core Preload Rules
| Rule | Description |
|---|---|
| Single Cache | The SDK caches only one ad per ad unit; cannot request another preload until the current one has been played. |
| Preload Next After Playback | After an ad is displayed, you can call PreloadAd() again to preload the next ad. |
| ID and Type Must Match | The adUnitId and adType in ShowPreloadAd() must exactly match those in PreloadAd(). |
Best Practice Example
Scenario: Rewarded video ad used to claim double rewards after a level ends.
plaintext
Before level starts
↓
Call PreloadAd() to preload rewarded video
↓
Player completes level
↓
Call ShowPreloadAd() to display ad
↓
Ad playback complete
↓
Start next level
↓
Call PreloadAd() again to preload the next one
Preload Interface
void PreloadAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type |
| appType | int | Required | Application Type: 1: Apps |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
Complete Code Example (Interstitial Ad)
//Calling an ad on the UI thread
case ID_BTN_AD4PRELOAD: {
nlohmann::json json_obj = {
{"unitId", InterstitialUnitId},
{"appType", 1},
{"adType", 4}
};
std::string jsonStr = json_obj.dump();
preloadAd(jsonStr.c_str());
break;
}
void preloadAd(const char* json)
{
try
{
// Ensure that COM has been initialized before the call
if (!g_comInitialized) {
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr)) {
g_comInitialized = true;
}
}
PreloadAd func = (PreloadAd)GetProcAddress(hDLL, "PreloadAd");
if (func) {
func(json);
}
}
catch (...)
{
}
}
// Ad Preload Callback Event
void onAdPreloadEvent(char* s) {
AppendLog(L"onAdPreloadEvent: %hs", s);
//eg.s = {"unitId":"a9bd7d57faef4f8cb016979284c86102","advertStatus":1,"displayStatus":0}
//...
nlohmann::json json_obj = nlohmann::json::parse(s);
std::string unitId = json_obj["unitId"];
std::int32_t adStatus = json_obj["advertStatus"];
if (adStatus == 1)
{
// Ad loaded successfully
if (unitId == InterstitialUnitId)
{
EnableWindow(g_hBtnInterstitialAdShow, TRUE);
}
else if (unitId == RewardedUnitId)
{
EnableWindow(g_hBtnRewardedAdShow, TRUE);
}
}
}
// Display ads that have been successfully preloaded
int showPreloadAd(const char* json,HWND adBntHwnd)
{
try
{
if (!g_comInitialized) {
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr)) {
g_comInitialized = true;
}
}
ShowPreloadAd func = (ShowPreloadAd)GetProcAddress(hDLL, "ShowPreloadAd");
if (func) {
func(json);
AppendLog(L"show mg ad: success");
EnableWindow(adBntHwnd, FALSE);
}
}
catch (...)
{
}
return 0;
}
Show Preloaded Ad Interface
void ShowPreloadAd(const char* jsonParam)
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| unitId | string | Required | Unique identifier for the ad unit, 32-character lowercase alphanumeric string, obtained from the MG Ad backend. |
| adType | int | Required | Ad type: For Rewarded ads, please use 6 |
| handle | int | Required | Ad Container Handle |
| appType | int | Required | Application Type: 1: Apps, 2: Games developed using engines such as Cocos |
| media | string | Optional | Supported ad media types. this field is optional. If left empty, the system will randomly return one of the ad types currently enabled in the MG backend. Available values: ● image: Image ad, supported by default ● web: Web ad, requires permission from MG Product Manager ● video: Video ad, supported by default |
Return Value Description
The results of the call are returned via an asynchronous callback event.
⚠️ Note: Before calling this interface, ensure that the corresponding ad unit has been successfully preloaded via PreloadAd.
Code Examples
4.2.1 Display Preloaded Full-screen Ad
case ID_BTN_AD1PRESHOW: {
RECT clientRect;
if (GetClientRect(hWnd, &clientRect)) {
int clientWidth = clientRect.right - clientRect.left;
int clientHeight = clientRect.bottom - clientRect.top;
nlohmann::json json_obj = {
{"unitId", FullScreenAdUnitId},
{"appType", 1},
{"adType", 1},
{"handle", reinterpret_cast<int>(g_hwndMain)},
{"parentWidth", clientWidth},//The app's width and height must be passed to the splash screen, and the pre-caching interface also requires this information.
{"parentHeight", clientHeight}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hwndMain);
}
break;
}
4.2.2 Display Preloaded Banner Ad
CreateBannerAdPanel(hWnd);
int containerHandle = reinterpret_cast<int>(g_hPnlBanner);
nlohmann::json json_obj = {
{"unitId", BannerUnitId},
{"appType", 1},
{"adType", 3},//Banner
{"handle", containerHandle}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hPnlBanner);
break;
}
4.2.3 Display Preloaded Interstitial Ad
case ID_BTN_AD4PRESHOW: {
CreateInterstitialAdPannel(hWnd);
nlohmann::json json_obj = {
{"unitId", InterstitialUnitId},
{"appType", 1},
{"adType", 4},
{"handle", reinterpret_cast<int>(g_hPnlInterstitial)}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hBtnInterstitialAdShow);
break;
}
4.2.4 Display Preloaded Couplet Ad
csharp
case ID_BTN_AD5PRESHOW: {
CreateCoupletAdPannel(hWnd);
nlohmann::json json_obj = {
{"unitId", CoupletUnitId},
{"appType", 1},
{"adType", 5},
{"handle", reinterpret_cast<int>(g_hPnlCoupletLeft)},
{"handle2", reinterpret_cast<int>(g_hPnlCoupletRight)}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hPnlCoupletLeft);
break;
}
4.2.5 Display Preloaded Rewarded Ad
case ID_BTN_AD6PRESHOW: {
CreateRewardAdPannel(hWnd);
nlohmann::json json_obj = {
{"unitId", RewardedUnitId},
{"comment", "abc123"},
{"appType", 1},
{"adType", 6},
{"handle", reinterpret_cast<int>(g_hPnlReward)},
{"width", 1024},
{"height", 768}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hBtnRewardedAdShow);
break;
}
4.2.6 Display Preloaded Feed Ad
case ID_BTN_AD7PRESHOW: {
nlohmann::json json_obj = {
{"unitId", FeedUnitId},
{"comment", "abc123"},
{"appType", 1},
{"adType", 7},
{"handle", reinterpret_cast<int>(g_hPnlFeed)},
{"width", 400},
{"height", 50}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hPnlFeed);
break;
}
4.2.7 Display Preloaded Embeded Ad
case ID_BTN_AD7PRESHOW: {
nlohmann::json json_obj = {
{"unitId", EmbeddedUnitId},
{"appType", 1},
{"adType", 8},
{"handle", reinterpret_cast<int>(g_hPnlEmbedded)},
{"width", 200},
{"height", 200}
};
std::string jsonStr = json_obj.dump();
showPreloadAd(jsonStr.c_str(), g_hPnlEmbedded);
break;
}
Preload Feature Call Flow
plaintext
┌─────────────────────────────────────────────────────────────────┐
│ App Launch │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ Call OpenCmp() and Initialize() │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ SDK Initialization Complete │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ 【Preload Mode】Call PreloadAd() to preload ad │
│ (e.g., preload before level start) │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ Check if preload succeeded │
└─────────────┬───────────────────────────────┬───────────────────┘
↓ ↓
┌──────────────┐ ┌──────────────┐
│ Success(true)│ │Failure(false)│
└───────┬──────┘ └───────┬──────┘
↓ ↓
┌─────────────────────────┐ ┌─────────────────────────────┐
│Wait for ad display trigger│ │ use the standard ShowAd() │
│(e.g., after player clears level)│ or skip this ad display │
└─────────────┬───────────┘ └─────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ Call ShowPreloadAd() to display the preloaded ad │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ Ad display complete │
└─────────────────────────────┬───────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ Call PreloadAd() again to preload the next ad │
│ (prepare for the next display) │
└─────────────────────────────────────────────────────────────────┘
Frequently Asked Questions (FAQ)
Q1: Why must I create an ad unit in the backend first?
A: The ad unitID is the unique identifier for ad requests. It must be pre-created and configured with ad materials in the MG Ad backend to successfully request and display ads.
Q2: What should I do if ad display fails?
A: Common causes and solutions:
| Error Type | Solution |
|---|---|
| Incorrect ad unit ID | Verify the 32-character lowercase alphanumeric ID in the backend. |
| Network issues | Check device network connection. |
| No available ad materials | Contact MG Product Manager to add ad materials of the appropriate size and format. |
| Preload not completed | Ensure PreloadAd succeeded before calling ShowPreloadAd. |
Q3: How to grant rewards for rewarded video?
A: Check completeState.IsCompleted in the ShowRewardAd callback:
-
If true, the user watched the entire video and reward can be granted.
-
After granting the reward, you must call
ReportAdRewardFulfillment()to notify the MG backend for verification.
Q4: What are the benefits of the preload feature?
A:
-
Loads ad materials in advance, reducing user wait time.
-
Improves ad display success rate.
-
Suitable for scenarios requiring precise control over ad display timing.
Q5: Can I call ads before OpenCmp and Initialize are complete?
A: No. You must complete CMP and SDK initialization first to properly call ad functionality. Otherwise, ad requests may fail or cause compliance issues.
Q6: When should I use the preload feature?
A: Only when your app has integrated multiple ad platforms (e.g., using Pangle, YLH, MG, etc. simultaneously) is it recommended to use preload mode. For single-platform scenarios, directly using ShowAd() is sufficient.
Q7: Can preload cache multiple ads simultaneously?
A: No. Each ad unit caches only one ad; you cannot request another preload until the current one has been played. After an ad is displayed, call PreloadAd() again to preload the next one.
Q8: What if ShowPreloadAd() fails?
A: Suggested handling order:
-
Check whether the corresponding ad unit was preloaded successfully.
-
Check whether the ad unit ID matches.
-
Check whether the ad type matches.
-
Fall back to the normal ShowAd() mode.
-
Abandon this advertising display
Q9: What types of controls can be used as the Container for custom ads?
A: Supports Panel, ContentControl, UserControl, etc.
Q10: How do I actively close a currently displayed ad?
A: Simply remove the corresponding container control.