跳到主要内容

SDK初始化

简介

      在接入MG Ads SDK之前,首先需要进行SDK的初始化,初始化完成后,才可以配合后台系统使用本SDK的全部功能,在进入游戏后即进行SDK初始化。

SDK初始化

void InitMgAdSdk(HWND hWnd) {
if (hDLL) return;

hDLL = LoadLibrary(L"MgAdSDKCSharpDLL.dll");
if (hDLL) {
// Register the CMP callback event
if (auto func = (CmpClosedEvent)GetProcAddress(hDLL, "CmpClosedEvent")) //CMP已关闭
func(onCmpClosedEvent);

// Register the initialisation completion callback event
if (auto func = (InitCompleteEvent)GetProcAddress(hDLL, "InitCompleteEvent")) // 初始化完成后的回调函数
func(onInitCompleteEvent);
if (auto func = (AdCloseEvent)GetProcAddress(hDLL, "AdCloseEvent")) //广告关闭事件的回调函数
func(onAdCloseEvent);

//1.设置参数
setAppId(hDLL, YourAppId, YourSecretKey);

//2.首先判断是否需要弹出CMP
if (isOpenCmp(hDLL))
{
RECT clientRect;
if (GetClientRect(hWnd, &clientRect)) {
int panelWidth = clientRect.right - clientRect.left;
int panelHeight = clientRect.bottom - clientRect.top;

//2.1.创建CMP容器
HINSTANCE minstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
g_hPnlCmp = CreateWindowW(L"STATIC", L"This is a panel for CMP", WS_CHILD | WS_VISIBLE, 0, 0, panelWidth, 50, hWnd, (HMENU)3011, minstance, NULL);
BringWindowToTop(g_hPnlCmp);

//2.2.弹出CMP
nlohmann::json json_obj = {
{"handle", reinterpret_cast<int>(g_hPnlCmp)},
{"parentWidth", panelWidth},
{"parentHeight", panelHeight}
};
std::string jsonStr = json_obj.dump();
openCmp(hDLL, jsonStr.c_str());
}
}

//3.SDK initialisation
initialize(hDLL);
}
}

void initialize(HINSTANCE hdll) {
try
{
Initialize func = (Initialize)GetProcAddress(hdll, "Initialize");
func(YourAppId, YourSecretKey);
}
catch (const std::exception&)
{
}
}

//初始化完成的回调函数
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");

//退屏广告;Step1.初始化成功之后,加载退屏广告资源
setupExitAd(hDLL);

//向UI线程发消息,使其调用开屏广告
PostMessage(g_hwndMain, WM_SHOW_OPENSCREEN_ADVERT, 0, NULL);
}
}
catch (const std::exception&)
{
}
}

void onCmpClosedEvent(char* s) {
try
{
g_cmpChangedWidth = 0;
g_cmpChangedHeight = 0;

//在UI线程移除CMP控件
PostMessage(g_hwndMain, WM_DESTROY_CMP, 0, NULL);

AppendLog(L"CMP has been removed.");
}
catch (const std::exception&)
{
}
}

没有初始化成功的错误可能如下

● 网络故障,没有正确的网络支持

  ● UWP应用不支持VPN,本机开启了VPN软件

  ● AppId错误,请登录开发者后台检查应用设置

  ● 服务器问题,请检查result的错误信息,及时联系技术支持