‹ HMS Doc Home

Huawei Mobile Services Integration Guide

For the Lua version of cocos2d-x v3.x - (all other versions)

Integration

Open a terminal and use the following command to install the SDKBOX HMS plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import hms

Important Notice

Please make sure the following settings in your project to make the plugin work well.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't, cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations, you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This setting depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

Extra steps

Android Steps

you should add this code com.sdkbox.plugin.PluginHMS.ApplicationInit(this); to Application::onCreate. modification may like follow (create a new Application class if it not exist):

public class YourApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        com.sdkbox.plugin.PluginHMS.ApplicationInit(this); // add this line
    }

    ...
}

Configuration

SDKBOX Installer will automatically inject a sample configuration to your sdkbox_config.json, that you have to modify it before you can use it for your own app.

Here is an example of the HMS configuration.

"ios" :
{
    "hms":{
    }
},
"android":
{
    "hms":{
        "archive": true,
        "key": "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAn9U6yC1QI8cXGRkOQxO9QG/WV8dR4jZDCYt/GJBM4OTTtRZeAIEyVifGPutwMAkPBLgdUsJwHuA2t2jrBAi/nagYJvh8UIazKJv5C4Hykw5Z2iKTWMmiMK9rQ2tMtRTAMiY+LwfaOH2258bEyt8mDQxyG3aRSAH28mZki/nGEbNfx7ZY9By/SSkuaCEWRDNYdiWkGDuZLhf8D97DoJJc6tTnrDPmzf1QqkVDjjudkHJwgCMWpLVACzGGuo4YQYt98Pu9cqbiYWJqSHqEbPYN0AmGXdJw+tO5f1wPcZWnJhn4JqCFmD9i/dSENNJWXVDgJc0DG2PiWX5j+qUaT7WkZMs4/WFtL6VRdRUDzITqYwKUUBYENVvkfdKlhjh+6V4BFKPsipvjOsRdXDpZ7sC6MY/7yn0eMOH3RoIQoiWeGYkxRTkKhdm/QQ/Xv/dvMbiicsNmUIkBce3w4hQG9XlhgjNrl5rI4p9Ho3Stq48s7DJlhWuUE6pXcjo2TJUSJ9+nAgMBAAE=",
        "items": {
            "remove_ads": {
                "type": "non_consumable",
                "id": "com.sdkbox.test.app.sample.noad"
            },
            "coin": {
                "id": "com.sdkbox.test.app.sample.coin1"
            },
            "vip": {
                "type": "subs",
                "id": "com.sdkbox.test.app.sample.vip"
            }
        },
        "achievements": [{
            "name": "freshman",
            "id": "A7346279E90AB8910AAC0CB71E552BFA2505DFD7591C79457F84D6B95F50FFEC",
            "incremental": false
        }, {
            "name": "3shoot",
            "id": "BA8B1A486D422AEF28FF82F9BFF85C3F156824396E0BB62D92BECC63C3CAC46A",
            "incremental": true
        }, {
            "name": "5shoot",
            "id": "001D38EC9E1A80A52ED3F47BFBA35F4B5BDF3776180A2B9AD778800C45CD6540",
            "incremental": true
        }],
        "events": [{
            "name": "gencoin",
            "id": "912764D10F0988B9DCB041A4E6FE453BCBDEDC4E35708A60E33C2DEBF05F2D2E"
        }, {
            "name": "consumecoin",
            "id": "E8688F3D9625572F462F5999E7F83EB5628E0FC1F2044E84D026EC4AB33C09F5"
        }],
        "rankings": [{
            "name": "shooter",
            "id": "C8B96FA1EDFC2D87DFE9491409440E3F8B2E39AFB8BD7E95C3BE337FC207C253"
        }]
    }
}

And you must download agconnect-services.json from HMS developer site, and put it in proj.android/app.

HMS for iOS

Test HMS for android

  1. Create App in AppGallery
  2. Enable Module you need(enable AccountKit if you need)
  3. Configure app signature
  4. download app info agconnect-services.json

HMS official Document

Usage

Initialize HMS

sdkbox.PluginHMS:init()

Login

HMS provides three way to login.

sdkbox.PluginHMS:login(1);
sdkbox.PluginHMS:login(2);

Authorization is required only at the first sign-in to your app using a HUAWEI ID. Subsequent sign-ins using the same HUAWEI ID does not require any authorization.

sdkbox.PluginHMS:login(0);

onLogin will be triggered when HMS AccountKit reruns the login response.

HMS offical documentation

Logout

sdkbox.PluginHMS:logout();

Request Managed Products

sdkbox.PluginHMS:iapRequestProducts();

this method will trigger onIAPProducts event

Purchase Managed Product

sdkbox.PluginHMS:iapPurchase("coin");

this method will trigger onIAPPurchase event

Purchase Unmanaged Product

local productInfo = {
  priceType = 0, -- 0:consumable 1:non-consumable 2:subscription
  productName = 'product name',
  productId = 'product id',
  amount = '1.00',
  currency = 'CNY',
  country = 'CN',
  sdkChannel = '1', -- sdkChannel size must be between 0 and 4
  serviceCatalog = 'X58',
  reservedInfor = '{"a": 1, "b":"s"}', -- reservedInfor must be json string
  developerPayload = 'payload1'
};
sdkbox.PluginHMS:iapPurchaseWithPrice(JSON:encode(productInfo));

this method will trigger onIAPPurchase event

request owned purchase

will return current user own products, include non-consumable, subscription product and consumable product which have not be consumed.

sdkbox.PluginHMS:iapRequestOwnedPurchases();

this method will trigger onIAPOwnedPurchases event

consume product

sdkbox.PluginHMS:iapConsume(purchaseToken);

this method will trigger onIAPPConsume event

request owned purchase record

request current user's all purchase records.

sdkbox.PluginHMS:iapRequestOwnedPurchaseRecords(purchaseToken);

this method will trigger onIAPOwnedPurchaseRecords event

Player Info

GetPlayer Info

will trigger listener event onPlayerInfo

sdkbox.PluginHMS:playerRequestInfo();

GetPlayer ExtraInfo

Will return follow info of current player: isadult, playtime and so on will trigger listener event onPlayerExtraInfo

sdkbox.PluginHMS:playerRequestInfo();

Submit GameBegin

submit player game begin event. if your game will sell in china, you should submit game begin event. will trigger listener event onPlayerGameBegin

sdkbox.PluginHMS:playerSubmitGameBegin();

Submit GameEnd

submit player game begin event. if your game will sell in china, you should submit game end event.

will trigger listener event onPlayerGameEnd

sdkbox.PluginHMS:playerSubmitGameEnd();

Achievement

Request Achievement List

request achivement list, then you can show achievement list by yourself

will trigger listener event onAchievementList

sdkbox.PluginHMS:achievementRequestList();

AchievementShow

show achivement with hms default ui

will trigger listener event onAchievementShow

sdkbox.PluginHMS:achievementShow();

achievementVisualize

will trigger listener event onAchievementVisualize

sdkbox.PluginHMS:achievementVisualize();

achievementGrow

will trigger listener event onAchievementGrow

sdkbox.PluginHMS:achievementGrow();

achievementMakeSteps

will trigger listener event onAchievementMakeSteps

sdkbox.PluginHMS:achievementMakeSteps();

achievementReach

sdkbox.PluginHMS:achievementReach();

Event

eventGrow

sdkbox.PluginHMS:eventGrow();

eventRequestList

will trigger listener event onEventList

sdkbox.PluginHMS:eventRequestList();

Ranking

Check ranking switch status

before invoke ranking related api, you must make sure player is allow to open score.

will trigger listener event onRankingSwitchStatus

sdkbox.PluginHMS:rankingRequestSwitchStatus();

will trigger listener event onRankingSetSwitchStatus

sdkbox.PluginHMS:rankingSetSwitchStatus();

submit score

will trigger listener event onRankingSubmitScore

sdkbox.PluginHMS:rankingSubmitScore(rankingName, score, score_unit);

Show ranking

show ranking by self.

will trigger listener event onRankingList

local realtime = true; -- true, will request data from hms server; false, will use local cache data
sdkbox.PluginHMS:rankingRequestList(realtime, rankingName);

show with hms default ui

will trigger listener event onRankingShow

local timeDimension = 2; -- 0-> day, 1-> week, 2-> all time
sdkbox.PluginHMS:rankingShow(timeDimension, rankingName);

get scores

current player score

will trigger listener event onRankingCurPlayerScore

local timeDimension = 2; -- 0-> day, 1-> week, 2-> all time
sdkbox.PluginHMS:rankingRequestCurPlayerScore(rankingName, timeDimension);

request player centered score

will trigger listener event onRankingPlayerCenteredScores

local timeDimension = 2; -- 0-> day, 1-> week, 2-> all time
sdkbox.PluginHMS:rankingRequestPlayerCenteredScores(rankingName, timeDimension, realtime);

Archive

add archive

will trigger listener event onArchiveAdd

local bmBytes -- cover image data
local dataBytes -- archive binary data
sdkbox.PluginHMS:archiveAdd(playedTime, progress, description, supportCache,
                               bmBytes, bmBytesType,
                               dataBytes);

update archive

will trigger listener event onArchiveUpdate

local bmBytes -- cover image data
local dataBytes -- archive binary data
sdkbox.PluginHMS:archiveUpdate(archiveId,
                          playedTime, progress, description,
                          bmBytes, bmBytesType,
                          dataBytes);

load archive

will trigger listener event onArchiveLoad

local conflictPolicy = 3;
//-1 -> hms willn't hand conflict, 
//1  -> hms will resolved conflict by played time, 
//2  -> hms will resolved conflict by progress,
//3  -> hms will resolved conflict by last update time
sdkbox.PluginHMS:archiveLoad(archiveId, conflictPolicy);

BUOY

if you game sell in china, you should show buoy

sdkbox.PluginHMS:buoyShow();
//or
sdkbox.PluginHMS:buoyHide();

caceh ad

sdkbox.PluginHMS:adCache(adName);

show ad

if (sdkbox.PluginHMS:adIsAvailable(adName)) {
    sdkbox.PluginHMS:adShow(adName);
}

hide banner

sdkbox.PluginHMS:adHide(adName);

ad request settings (Optional)

--[[
adContentClassification:
  "W"->Content suitable for toddlers and older audiences;
 "PI"->Content suitable for kids and older audiences
  "J"->Content suitable for teenagers and older audiences.
  "A"->Content suitable only for adults.
   ""->Unknown rating.
]]--
sdkbox.PluginHMS:adSetAdContentClassification("A");

--[[
tagForUnderAgeOfPromise:
 0->Do not process ad requests as directed to users under the age of consent;
 1->Process ad requests as directed to users under the age of consent;
-1->Whether to process ad requests as directed to users under the age of consent is not specified;
]]--
sdkbox.PluginHMS:adSetTagForUnderAgeOfPromise(0);

--[[
tagForChildProtection:
 0->Do not process ad requests according to the COPPA;
 1->Process ad requests according to the COPPA;
-1->Whether to process ad requests according to the COPPA is not specified;
]]--
sdkbox.PluginHMS:adSetTagForChildProtection(0);

--[[
nonPersonalizedAd
 0->Request both personalized and non-personalized ads (default);
 1->Request only non-personalized ads;
]]--
sdkbox.PluginHMS:adSetNonPersonalizedAd(0);

reward ad setting (Optional)

reward data must be URL-encoded and length must be less than 1024

-- reward ad custom data
sdkbox.PluginHMS:adSetRewardData("cdata");

-- uid for reward ad
sdkbox.PluginHMS:adSetRewardUserId("uid666");

Handling HMS Events

This allows you to catch the HMS events so that you can perform operations based upon the response from your players and HMS servers.

all listener include code param, you can find code in follow url:

here we list a specific code:

sdkbox.PluginHMS:setListener(function(args)
    -- Account
    if "onLogin" == args.event then
        local code = args.code
        local msg = args.msg
        dump(args, "onLogin:")

    -- Player Info
    else if "onPlayerInfo" == args.event then
    else if "onPlayerExtraInfo" == args.event then
    else if "onPlayerGameBegin" == args.event then
    else if "onPlayerGameEnd" == args.event then

    -- IAP
    else if "onIAPReady" == args.event then
        local code = args.code
        local msg = args.msg
    else if "onIAPProducts" == args.event then
        local code = args.code
        local msg = args.msg
    else if "onIAPPurchase" == args.event then
        local code = args.code
        local msg = args.msg
    else if "onIAPPConsume" == args.event then
        local code = args.code
        local msg = args.msg
    else if "onIAPOwnedPurchases" == args.event then
        local code = args.code
        local msg = args.msg
    else if "onIAPOwnedPurchaseRecords" == args.event then
        local code = args.code
        local msg = args.msg

    -- Achievement
    else if "onAchievementList" == args.event then
    else if "onAchievementShow" == args.event then
    else if "onAchievementVisualize" == args.event then
    else if "onAchievementGrow" == args.event then
    else if "onAchievementMakeSteps" == args.event then

    -- Event
    else if "onEventList" == args.event then

    -- Ranking
    else if "onRankingSwitchStatus" == args.event then
    else if "onRankingSetSwitchStatus" == args.event then
    else if "onRankingSubmitScore" == args.event then
    else if "onRankingShow" == args.event then
    else if "onRankingList" == args.event then
    else if "onRankingCurPlayerScore" == args.event then
    else if "onRankingPlayerCenteredScores" == args.event then
    else if "onRankingMoreScores" == args.event then
    else if "onRankingTopScores" == args.event then

    -- Archive
    else if "onArchiveLimitThumbnailSize" == args.event then
    else if "onArchiveLimitDetailsSize" == args.event then
    else if "onArchiveAdd" == args.event then
    else if "onArchiveShow" == args.event then
    else if "onArchiveSummaryList" == args.event then
    else if "onArchiveSelect" == args.event then
    else if "onArchiveThumbnail(code, errorOrJson, co" == args.event then
    else if "onArchiveUpdate" == args.event then
    else if "onArchiveLoad(code, errorOrJson, cont" == args.event then
    else if "onArchiveRemove" == args.event then

    -- Game Stats
    else if "onGamePlayerStats" == args.event then
    else if "onGameSummary" == args.event then

    -- Ad
    else if "onAdClose" == args.event then
    else if "onAdFail" == args.event then
    else if "onAdLeave" == args.event then
    else if "onAdOpen" == args.event then
    else if "onAdLoad" == args.event then
    else if "onAdClick" == args.event then
    else if "onAdImpression" == args.event then
    else if "onAdReward" == args.event then

    else
        print("unknow event ", args.event)
    end
end)

Remote Configuration

Optionally, you can choose to use SDKBOX LiveOps to remotely update this plugin's configuration. Learn more

API Reference

Methods

sdkbox.PluginHMS:setGDPR(enabled)

Set GDPR

sdkbox.PluginHMS:init()

initialize the plugin instance.

sdkbox.PluginHMS:setListener(listener)

Set listener to listen for adcolony events

sdkbox.PluginHMS:login(loginType)

HMS provider three way to login loginType: 0, slient login 1, login with HuaweiID(ID Token) 2, login with HuaweID(Authorization Code)

sdkbox.PluginHMS:logout()

logout HMS

sdkbox.PluginHMS:playerRequestInfo()

request current player info

sdkbox.PluginHMS:playerRequestExtraInfo()

request player extra info

sdkbox.PluginHMS:playerSubmitGameBegin()

submit game begin event

sdkbox.PluginHMS:playerSubmitGameEnd()

submit game end event

sdkbox.PluginHMS:iapRequestProducts()
sdkbox.PluginHMS:iapPurchase(name)
sdkbox.PluginHMS:iapPurchaseWithPrice(productJson)
sdkbox.PluginHMS:iapRequestOwnedPurchases()
sdkbox.PluginHMS:iapConsume(purchaseToken)
sdkbox.PluginHMS:iapRequestOwnedPurchaseRecords()
sdkbox.PluginHMS:achievementRequestList()
sdkbox.PluginHMS:achievementShow()
sdkbox.PluginHMS:achievementVisualize(name)
sdkbox.PluginHMS:achievementGrow(achiveName, steps)
sdkbox.PluginHMS:achievementMakeSteps(achiveName, steps)
sdkbox.PluginHMS:achievementReach(achiveName)
sdkbox.PluginHMS:eventGrow(eventName, amount)
sdkbox.PluginHMS:eventRequestList(realtime, eventNamas)
sdkbox.PluginHMS:rankingRequestSwitchStatus()

request if player allow open score in ranking

sdkbox.PluginHMS:rankingSetSwitchStatus(status)

request if player allow open score in ranking status: 0->player allow submit score, 1->player not allow submit score

sdkbox.PluginHMS:rankingSubmitScore(rankingName, score, unit)

submit score to ranking

sdkbox.PluginHMS:rankingShow(timeDimension, rankingName)

use hms's ui to show ranking

sdkbox.PluginHMS:rankingRequestList(realtime, rankingName)

request ranking list

sdkbox.PluginHMS:rankingRequestCurPlayerScore(rankingName, timeDimension)

request current player ranking score

sdkbox.PluginHMS:rankingRequestPlayerCenteredScores(rankingName,
                                                     timeDimension,
                                                     size,
                                                     realtime)

request player centered scores

sdkbox.PluginHMS:rankingRequestMoreScores(rankingName,
                                           timeDimension,
                                           offset,
                                           pageSize,
                                           pageDirection)

request more scores

sdkbox.PluginHMS:rankingRequestTopScores(rankingName,
                                          timeDimension,
                                          offset,
                                          pageSize,
                                          pageDirection)

submit score to ranking

sdkbox.PluginHMS:archiveRequestLimitThumbnailSize()

get thumbnail max size

sdkbox.PluginHMS:archiveRequestLimitDetailsSize()

get detail max size

sdkbox.PluginHMS:archiveAdd(playedTime, progress, description, supportCache,
                               bmBytes, bmBytesType,
                               dataBytes)

add archive bmBytes: cover image data dataBytes: archive data

sdkbox.PluginHMS:archiveShow(title, allowAdd, allowDelete, pageSize)

use hms's default ui to show archive

sdkbox.PluginHMS:archiveRequestSummaryList(realtime)

request archive summay list, developer can show custome archive list with the returned data

sdkbox.PluginHMS:archiveRequestThumbnail(archiveId)

request archive cover thumbnail

sdkbox.PluginHMS:archiveUpdate(archiveId,
                               playedTime, progress, description, supportCache,
                               bmBytes, bmBytesType,
                               dataBytes)

update archive bmBytes: cover image data dataBytes: archive data

sdkbox.PluginHMS:archiveLoad(archiveId, conflictPolicy)

load archive

sdkbox.PluginHMS:archiveRemove(archiveId)

remvoe archive

sdkbox.PluginHMS:gamePlayerStatsRequest(realtime)

request game player statistics

sdkbox.PluginHMS:gameSummaryRequest(realtime)

request game summary

sdkbox.PluginHMS:buoyShow()
sdkbox.PluginHMS:buoyHide()
sdkbox.PluginHMS:adCache(name)
sdkbox.PluginHMS:adShow(name)
sdkbox.PluginHMS:adHide(name)
sdkbox.PluginHMS:adIsAvailable(name)
sdkbox.PluginHMS:adSetRewardData(custom_data)
sdkbox.PluginHMS:adSetRewardUserId(user_id)
sdkbox.PluginHMS:adSetAdContentClassification(adContentClassification)
sdkbox.PluginHMS:adSetTagForUnderAgeOfPromise(tagForUnderAgeOfPromise)
sdkbox.PluginHMS:adSetTagForChildProtection(tagForChildProtection)
sdkbox.PluginHMS:adSetNonPersonalizedAd(nonPersonalizedAd)

Listeners

onLogin(code, errorOrJson)
onPlayerInfo(code, errorOrJson)
onPlayerExtraInfo(code, errorOrJson)
onPlayerGameBegin(code, errorOrJson)
onPlayerGameEnd(code, errorOrJson)
onIAPReady(code, errorOrJson)
onIAPProducts(code, errorOrJson)
onIAPPurchase(code, errorOrJson)
onIAPConsume(code, errorOrJson)
onIAPOwnedPurchases(code, errorOrJson)
onIAPOwnedPurchaseRecords(code, errorOrJson)
onAchievementList(code, errorOrJson)
onAchievementShow(code, errorOrJson)
onAchievementVisualize(code, errorOrJson)
onAchievementGrow(code, errorOrJson)
onAchievementMakeSteps(code, errorOrJson)
onEventList(code, errorOrJson)
onRankingSwitchStatus(code, errorOrJson)
onRankingSetSwitchStatus(code, errorOrJson)
onRankingSubmitScore(code, errorOrJson)

callback for rankingSubmitScore

onRankingShow(code, errorOrJson)

callback for rankingShow

onRankingList(code, errorOrJson)

callback for rankingRequestList

onRankingCurPlayerScore(code, errorOrJson)

callback for rankingRequestCurPlayerScore

onRankingPlayerCenteredScores(code, errorOrJson)

callback for rankingRequestPlayerCenteredScores

onRankingMoreScores(code, errorOrJson)

callback for rankingRequestMoreScores

onRankingTopScores(code, errorOrJson)

callback for rankingRequestTopScores

onArchiveLimitThumbnailSize(code, errorOrJson)

callback for archiveRequestLimitThumbnailSize

onArchiveLimitDetailsSize(code, errorOrJson)

callback for archiveRequestLimitDetailsSize

onArchiveAdd(code, errorOrJson)

callback for archiveAdd

onArchiveShow(code, errorOrJson)

callback for archiveShow

onArchiveSummaryList(code, errorOrJson)

callback for archiveRequestSummaryList

onArchiveSelect(code, errorOrJson)

callback when user select archive

onArchiveThumbnail(code, errorOrJson, coverData, coverDataLen)

callback for archiveRequestThumbnail

onArchiveUpdate(code, errorOrJson)

callback for archiveUpdate

onArchiveLoad(code, errorOrJson, contentData, contentDataLen)

callback for archiveLoad

onArchiveRemove(code, errorOrJson)

callback for archiveRemove

onGamePlayerStats(code, errorOrJson)

callback for gamePlayerStatsRequest

onGameSummary(code, errorOrJson)

callback for gameSummaryRequest

onAdClose(code, errorOrJson)
onAdFail(code, errorOrJson)
onAdLeave(code, errorOrJson)
onAdOpen(code, errorOrJson)
onAdLoad(code, errorOrJson)
onAdClick(code, errorOrJson)
onAdImpression(code, errorOrJson)
onAdReward(code, errorOrJson)

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of the HMS bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginHMS.framework

The above frameworks depend upon other frameworks. You also need to add the following system frameworks, if you don't already have them:

SystemConfiguration.framework

Copy all source and header files from plugin/luabindings/ to your projects Classes folder.

Add these same files, that you just copied, to Xcode by either dragging and dropping them into Xcode or by using File -> Add files to....

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy jar files

Copy the following jar files from plugin/android/libs folder of this bundle into your project's /libs folder.

PluginHMS.jar

sdkbox.jar

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Edit build.gradle

your modification maybe look like following:

project root gradle file


buildscript {
    repositories {
        google()
        jcenter()
        maven { url 'https://developer.huawei.com/repo/' } // for hms
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
        classpath 'com.huawei.agconnect:agcp:1.2.1.301' // for hms
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://developer.huawei.com/repo/' } // for hms
    }
}

application's build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect' // for hms

...

dependencies {
    ...
    implementation 'com.huawei.hms:base:4.0.4.301' // for hms
    implementation 'com.huawei.hms:hwid:4.0.4.300' // for hms
    implementation 'com.huawei.hms:iap:4.0.2.300' // for hms
    implementation 'com.huawei.hms:game:4.0.3.301' // for hms
}

Edit AndroidManifest.xml

Include the following permissions above the application tag:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING"/>

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Add additional dependencies to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginHMS
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./sdkbox)
$(call import-module, ./pluginhms)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./pluginhms)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 - v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Copy all source and header files from plugin/luabindings/ to your projects Classes folder.

Add all .cpp files, that you just copied, to Android.mk in the LOCAL_SRC_FILES section. Example

LOCAL_SRC_FILES := hellocpp/main.cpp \
                ../../Classes/AppDelegate.cpp \
                ../../Classes/HelloWorldScene.cpp \
                                ../../Classes/NewSourceFile.cpp

Modify AppActivity.java

Plugin >= 2.4.0.3

  1. Find the AppActivity.java
find . -name "AppActivity.java"
  1. Replace extends Cocos2dxActivity with extends com.sdkbox.plugin.SDKBoxActivity

Example of the directory where the AppActivity.java file is located:

cpp
  - proj.android/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android-studio/app/src/org/cocos2dx/cpp/AppActivity.java
  - proj.android/app/src/org/cocos2dx/cpp/AppActivity.java ( from cocos2d-x 3.17)

lua
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/lua/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/lua/AppActivity.java (from cocos2d-x 3.17)

js
  - frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java
  - frameworks/runtime-src/proj.android/app/src/org/cocos2dx/javascript/AppActivity.java ( from cocos2d-x 3.17)

Plugin < 2.4.0.3

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Proguard (optional)

proguard.config=proguard.cfg
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# HMS
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}

#sdkbox
-keep public class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.