What Is HUAWEI Game Service?

HUAWEI Game Service is a service provided by Huawei that allows for efficient game app development. With HUAWEI Game Service, you can enable users to sign in to your games using HUAWEI IDs, for optimally convenient game promotion that leverages Huawei's enormous user base.

What You Will Create

In this codelab, you will create an Android app that implements simple game interactions. The app will:

What You Will Learn

What You Will Need

Development Environment and Skill Requirements

Device Requirements

Creating an App and Obtaining the Configuration File

Create an app in AppGallery Connect and obtain the project configuration file agconnect-services.json. The procedure is as follows:

For details, please refer to HMS Core Integration Preparation.

Enabling HUAWEI Game Service

  1. Sign in to AppGallery Connect, click My projects, find your project, and click your desired app. On the page that is displayed, go to Project Setting > Manage APIs.
  2. Toggle the Huawei Account and Game Service switches.

Integrating the HMS Core SDK

For Android Studio, Huawei provides the HMS Core SDK that can be integrated by using the Maven repository. Before developing your game app, you will need to integrate the HMS Core SDK into your Android Studio project.

  1. Sign in to AppGallery Connect, click My projects, find your project, and click your desired app. On the page that is displayed, go to Project Setting > General information.
  2. In the App information area, click agconnect-services.json to download the configuration file.
  3. Copy the agconnect-service.json file to the project root directory.
  4. Open the Android Studio project-level build.gradle file.
  5. In the build.gradle file of your Android Studio project, add the following configurations.
    allprojects { repositories { google() jcenter() maven {url 'https://developer.huawei.com/repo/'} } } buildscript { repositories { google() jcenter() maven {url 'https://developer.huawei.com/repo/'} } } buildscript { dependencies { classpath 'com.android.tools.build:gradle:3.4.2' classpath 'com.huawei.agconnect:agcp:1.3.1.300' } }
  6. Open the Android Studio app-level build.gradle file.
  7. In the build.gradle file in the app directory of your Android Studio project, add the following configurations.
    Replace {version} of hwid with the latest version of HUAWEI Account Kit. For details, please refer to Adding Build Dependencies.
    Replace {version} of game with the latest version of HUAWEI Game Service. For details, please refer to Adding Build Dependencies.
    apply plugin: 'com.huawei.agconnect' dependencies { implementation'com.huawei.hms:hwid:{version}' implementation'com.huawei.hms:game:{version}' }
  8. Click Sync Now to synchronize the configurations.

Configuring Obfuscation Scripts

  1. Open proguard-rules.pro, the obfuscation configuration file of your Android Studio project.
  2. Add obfuscation configurations.
    -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.**{*;} -keep class com.huawei.gamebox.plugin.gameservice.**{*;} -keep interface com.huawei.hms.analytics.type.HAEventType{*;} -keep interface com.huawei.hms.analytics.type.HAParamType{*;} -keep class com.huawei.hms.analytics.HiAnalyticsTools{ public static void enableLog(); public static void enableLog(int); } -keep class com.huawei.hms.analytics.HiAnalyticsInstance{*;} -keep class com.huawei.hms.analytics.HiAnalytics{*;}

A game app interacts with Huawei game server mainly for game sign-in and game addiction prevention functions. In this codelab, you can create a layout page in your Android Studio project and design the UI according to the following figure.

Step 1 Import related classes.

import com.huawei.hmf.tasks.OnFailureListener; import com.huawei.hmf.tasks.OnSuccessListener; import com.huawei.hmf.tasks.Task; import com.huawei.hms.common.ApiException; import com.huawei.hms.jos.JosApps; import com.huawei.hms.jos.JosAppsClient; import com.huawei.hms.jos.games.Games; import com.huawei.hms.jos.games.PlayersClient; import com.huawei.hms.jos.games.buoy.BuoyClient; import com.huawei.hms.jos.games.player.Player; import com.huawei.hms.jos.games.player.PlayerExtraInfo; import com.huawei.hms.support.hwid.HuaweiIdAuthManager; import com.huawei.hms.support.hwid.request.HuaweiIdAuthParams; import com.huawei.hms.support.hwid.request.HuaweiIdAuthParamsHelper; import com.huawei.hms.support.hwid.result.AuthHuaweiId; import com.huawei.hms.support.hwid.service.HuaweiIdAuthService;

Step 2 Register the callback listening function of the activity in the onCreate method of the Application.

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); HuaweiMobileServicesUtil.setApplication(this); } @Override public void onTerminate() { super.onTerminate(); } }

Step 3 Initialize the Game Service SDK upon game launch.

/** * SDK initialization */ private void init() { JosAppsClient appsClient = JosApps.getJosAppsClient(this); appsClient.init(); showLog("init success"); }

Step 4 Verify the HUAWEI ID used for sign-in.

/** * When a player signs in, you need to call the HUAWEI ID sign-in verification API. If the verification is successful, call the getcurrentPlayer API to obtain player information. * 1. Call the silent sign-in API of the HUAWEI ID sign-in API so that the sign-in page will not be displayed for a game to which a player has already signed in. * 2. When silent sign-in fails, it indicates that this is the player's first sign-in and authorization from the player is required. In this case, in the callback, the explicit sign-in API is called to display the sign-in authorization page for sign-in verification. * The sign-in API is called in onActivity. Then you can call the API for obtaining player information. */ public void signIn() { Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.getService(this, getHuaweiIdParams()).silentSignIn(); authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() { @Override public void onSuccess(AuthHuaweiId authHuaweiId) { Log.i(TAG, "silentsignIn success"); Log.i(TAG, "display:" + authHuaweiId.getDisplayName()); login(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { ApiException apiException = (ApiException) e; Log.i(TAG, "signIn failed:" + apiException.getStatusCode()); Log.i(TAG, "start getSignInIntent"); //Sign in explicitly. The sign-in result is obtained in onActivityResult. HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, getHuaweiIdParams()); startActivityForResult(service.getSignInIntent(), 6013); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 6013) { if (null == data) { showLog("signIn inetnt is null"); return; } String jsonSignInResult = data.getStringExtra("HUAWEIID_SIGNIN_RESULT"); if (TextUtils.isEmpty(jsonSignInResult)) { showLog("signIn result is empty"); return; } try { HuaweiIdAuthResult signInResult = new HuaweiIdAuthResult().fromJson(jsonSignInResult); if (0 == signInResult.getStatus().getStatusCode()) { showLog("signIn success."); showLog("signIn result: " + signInResult.toJson()); } else { showLog("signIn failed: " + signInResult.getStatus().getStatusCode()); } } catch (JSONException var7) { showLog("Failed to convert json from signInResult."); } } }

Step 5 Obtain player information.

/** * Obtain player information. */ public void login() { playersClient = Games.getPlayersClient(this); Task<Player> playerTask = playersClient.getCurrentPlayer(); playerTask.addOnSuccessListener(new OnSuccessListener<Player>() { @Override public void onSuccess(Player player) { playerID = player.getPlayerId(); Log.i(TAG, "getPlayerInfo Success, player info: " + player.getPlayerId()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { // Failed to obtain player information. if (e instanceof ApiException) { Log.e(TAG, "getPlayerInfo failed, status: " + ((ApiException) e).getStatusCode()); } } }); }

Step 1 When a player enters the game, report a game entering event.

/** * Report the game addiction prevention event start time. */ private void timeReportStart() { if (playersClient == null) { Log.i(TAG, "playersClient is null, please init playersClient first"); login(); return; } if (playerID == null) { Log.i(TAG, "playerID is null, please getcurrentPlayer login first"); login(); return; } String uid = UUID.randomUUID().toString(); Task<String> task = playersClient.submitPlayerEvent(playerID, uid, "GAMEBEGIN"); task.addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String jsonRequest) { try { JSONObject data = new JSONObject(jsonRequest); sessionId = data.getString("transactionId"); } catch (JSONException e) { showLog("parse jsonArray meet json exception"); return; } showLog("submitPlayerEvent traceId: " + jsonRequest); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { String result = "rtnCode:" + ((ApiException) e).getStatusCode(); showLog(result); } } }); }

Step 2 When the game ends or is suspended, report a game exit event.

/** * Report the game addition prevention end time. * sessionId: The session ID is returned in the callback for a game entering event and will be used to calculate the played time when a game exit event is reported. */ private void timeReportEnd() { if (playersClient == null) { Log.i(TAG, "playersClient is null, please init playersClient first"); login(); return; } if (playerID == null) { Log.i(TAG, "playerID is null, please getcurrentPlayer login first"); login(); return; } if (sessionId == null) { Log.i(TAG, "sessionId is null, please submitPlayerEvent Begin first"); login(); return; } Task<String> task = playersClient.submitPlayerEvent(playerID, sessionId, "GAMEEND"); task.addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String s) { showLog("submitPlayerEvent traceId: " + s); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { String result = "rtnCode:" + ((ApiException) e).getStatusCode(); showLog(result); } } }); }

Step 3 Periodically call the PlayersClient.getPlayerExtraInfo method to query the additional information about the player. The method can be called at least every 10 minutes. It is recommended that you call this method every 15 minutes.

/** * Query game addiction prevention event reporting details. * If a player is a minor, call PlayerExtraInfo.getPlayerDuration to query the latest accumulated played time of the player on the current day. * Your game needs to perform game addiction prevention on minor players based on the accumulated played time. You need to implement the prevention logic based on your game. */ private void getPlayerExfra() { if (playersClient == null) { Log.i(TAG, "playersClient is null, please init playersClient first"); login(); return; } if (sessionId == null) { Log.i(TAG, "sessionId is null, please submitPlayerEvent Begin first"); login(); return; } Task<PlayerExtraInfo> task = playersClient.getPlayerExtraInfo(sessionId); task.addOnSuccessListener(new OnSuccessListener<PlayerExtraInfo>() { @Override public void onSuccess(PlayerExtraInfo extra) { if (extra != null) { showLog("IsRealName: " + extra.getIsRealName() + ", IsAdult: " + extra.getIsAdult() + ", PlayerId: " + extra.getPlayerId() + ", PlayerDuration: " + extra.getPlayerDuration()); } else { showLog("Player extra info is empty."); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { if (e instanceof ApiException) { String result = "rtnCode:" + ((ApiException) e).getStatusCode(); showLog(result); } } }); }
  1. Add your HUAWEI ID as a tester account by referring to Creating a Tester Account.
  2. Run your Android Studio project and generate the APK. Then, install the APK on your mobile phone for testing.
  3. Test the sign-in function.
  4. On the home page of your game, tap Init, SignIn, and GetCurrentPlayer in sequence to check whether they can work properly.

  5. Test the game addiction prevention function.
  6. On the home page of your game, tap Init, SignIn, GetCurrentPlayer, and SubmitPlayerEvent in sequence to check whether they can work properly.

    Tap SubmitPlayerEvent_End and GetPlayerExtraInfo to test other addiction prevention functions. All APIs will generate logs.

  7. View Logcat logs by searching the keyword Game_codeLab.
  8. Tag: Game_codeLab

Well done. You have successfully built a game app and learned how to:

Game APIs

Download the source code for the demo that is used in this codelab.

Download Source Code

Code copied