Intermediate: Integration of Huawei Game Services in Flutter (Cross platform) - Huawei Developers

Introduction
In this article, we will be integrating Huawei Game Services kit in flutter application. You will have access to range of development capabilities. You can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login game using Huawei IDs. You can also use the service to quickly implement achievements, game events, and game addiction prevention functions and perform in-depth game operations based on user and content localization.
Huawei Game Services Capabilities
Game Login
Achievements
Floating window*
Game Addiction prevention*
Events
Leaderboards
Save Games*
Player statistics*
Access to Basic Game Information*
Note: Restricted to regions (*)
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone with API 4.x.x or above (with the USB cable),Which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project.
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies.
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: gameservice234demo
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_account:
path: ../huawei_account
huawei_gameservice:
path: ../huawei_gameservice
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
How do I launch or initialize the game?
Code:
void init() async {
await JosAppsClient.init();
}
Use Huawei ID for login
Code:
Future<void> login() async {
helper = new HmsAuthParamHelper()
..setIdToken()
..setAccessToken()
..setAuthorizationCode()
..setEmail()
..setProfile();
huaweiId = await HmsAuthService.signIn(authParamHelper: helper);
if (huaweiId != null) {
setState(() {
isLoggedIn = true;
msg = huaweiId!.displayName;
loginLabel = "Logged in as";
print(msg);
});
getPlayer();
} else {
setState(() {
msg = " Inside else ";
});
}
}
How do I get Achievements list?
Code:
Future<void> getAchievements() async {
try {
List<Achievement> result =
await AchievementClient.getAchievementList(true);
print("Achievement:" + result.toString());
} on PlatformException catch (e) {
print("Error on getAchievementList API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I displaying the Achievements List Page of HUAWEI AppAssistant using Intent?
Code:
void showAchievementsIntent() {
try {
AchievementClient.showAchievementListIntent();
} on PlatformException catch (e) {
print("Error on showAchievementListIntent API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I call Floating window?
Code:
try {
await BuoyClient.showFloatWindow();
} on PlatformException catch (e) {
print("Error on showFloatWindow API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I get All Events?
Code:
Future<void> getEvents() async {
try {
List<GameEvent> result = await EventsClient.getEventList(true);
print("Events: " + result.toString());
} on PlatformException catch (e) {
print(
"Error on getEventList API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I submit an Event?
Code:
Future<void> sendEvent(String eventId) async {
try {
await EventsClient.grow(eventId, 1);
print("************** Event sent **************");
} on PlatformException catch (e) {
print(
"Error on grow API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I get All Leaderboard data?
Code:
Future<void> getLeaderboardList() async {
// check the leaderboard status
int result = await RankingClient.getRankingSwitchStatus();
// set leaderboard status
int result2 = await RankingClient.setRankingSwitchStatus(1);
List<Ranking> rankings = await RankingClient.getAllRankingSummaries(true);
print(rankings);
}
How do I submit the ranking score?
Code:
try {
int score = 102;
RankingClient.submitRankingScores(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitRankingScores API, Error: ${e.code}, Error Description:${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
Or
try {
int score = 125;
ScoreSubmissionInfo result = await RankingClient.submitScoreWithResult(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitScoreWithResult API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I displaying the Leaderboard List Page of HUAWEI AppAssistant using Intent?
Code:
void showLeaderboardIntent() {
try {
RankingClient.showTotalRankingsIntent();
} on PlatformException catch (e) {
print("Error on showLeaderboardListIntent API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
Result
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path in yaml.
Make sure that plugin unzipped in parent directory of project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in Ag-connect.
Conclusion
In this article, we have learnt how to integrate capabilities of Huawei Game Services kit in flutter application. Yu can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login game using Huawei IDs and achieve by implementing its capabilities in your application. Similar way you can use Huawei Game Services as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei Game Services capabilities in flutter.
Reference
GameServices Kit
Plutter Plugin
Original Source

Useful sharing, thanks

Related

How to use HMS IAP Plugin with Ionic?

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
While working with Ionic, it is recommended to use the Capacitor for new Ionic apps but sometimes you need to use some Cordova or Ionic Native plugins. In this guide you will learn how to use HMS IAP Cordova Plugin with an Ionic Capacitor application.
In order to use IAP Plugin with any application, you have to create an application on Huawei Developer Console and add some products.
You can read this guide for further details to create an application and add purchasable products to work with.
Huawei In-App Purchases
Huawei In-App Purchases (IAP) provides multiple payment methods for global payments and can be easily integrated into your application to help increase your revenue. Users can purchase a variety of products and services, including popular virtual products and subscriptions, from within your direct application.
Create an Application with Ionic
Install the Ionic CLI with npm if you haven’t already.
Code:
ionic start HMS-IAP-Demo blank --capacitor
cd HMS-IAP-Demo
npm run build
Add your agconnect-services.json and keystore files to project folder as explained in the guide I mentioned above.
Add the AppID you got from the Huawei Developer console to the AndroidManifest.xml file. (inside application tag)
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="appid=102461279">
</meta-data>
Add HMS IAP Cordova Plugin & Ionic Native
Code:
npm i @hmscore/cordova-plugin-hms-iap --save
npm i @ionic-native/core --save-dev
Copy the “ionic/dist/hms-in-app-purchases” folder from library in node_modules to the “node_modules/@ionic-native” folder in your ionic project.
Code:
ionic capacitor add add android
ionic capacitor sync
ionic capacitor build android
Run the project on a connected device
Run the Ionic application with the command below to try the application with a Huawei device. We’re using the --livereload and --external options to see changes on tthe device when changes in the app are detected.
Code:
ionic capacitor run android --livereload --external
Exploring IAP Library
You have to login with your Huawei ID on the device you’re going to install application. Otherwise, you will get an error. (Error Code: 60050). You can check the error details and other error codes here.
Adding Library to Providers
You have to add library to the providers section in app.module.ts before using it.
Code:
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
@NgModule({
...
providers: [
HMSInAppPurchases,
],
bootstrap: [AppComponent]
})
export class AppModule {}
Checking Environment
Before fetching the products, you should check the environment is ready.
Code:
import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage {
constructor(public iap: HMSInAppPurchases) { }
async ngOnInit() {
try {
let message = await this.iap.isEnvReady();
console.log(message);
} catch (error) {
console.error(error);
}
}
}
Fetching Products
If you have configured products in AppGallery Connect, you need to use the obtainProductInfo API to obtain details of these products.
Perform the following steps:
Construct a ProductInfoReq object and pass the product ID that has been defined and taken effect in AppGallery Connect to the ProductInfoReq object, and specify priceType for a product. “priceType” is type of the product. Check the code below for price types and their integer equivalents.
If the operation is successful, obtainProductInfo will return a ProductInfoResult object that contains productInfoList. You can use it to display the product information within your application.
Code:
import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';
const DEVELOPERPAYLOAD = "HMSCoreDeveloper"
const DEVELOPERCHALLENGE = "HMSCoreDeveloperChallenge"
const PRICETYPE = {
CONSUMABLE : 0,
NONCONSUMABLE : 1,
SUBSCRIPTION : 2,
}
const PRODUCTS = {
consumable: {
type: PRICETYPE.CONSUMABLE,
products: [{
id: 'test',
name: 'Consumable Item'
}]
},
nonconsumable: {
type: PRICETYPE.NONCONSUMABLE,
products: [{
id: 'non_consumable_item_1',
name: 'Non Consumable Item'
}, ]
},
subscription: {
type: PRICETYPE.SUBSCRIPTION,
products: [{
id: 'subscription_item_1',
name: 'Subscription Item'
}, ]
},
}
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private iap: HMSInAppPurchases) {}
ngOnInit() {
...
this.getProductsInformation();
}
getProductsInformation = () => {
Object.keys(PRODUCTS).map(async product_type=> {
await this.obtainProductInfoFromType(product_type);
});
}
obtainProductInfoFromType = async (product_type) => {
try {
let products = await this.iap.obtainProductInfo({
priceType: PRODUCTS[product_type].type,
productList: PRODUCTS[product_type].products.map(p=>p.id)
});
console.log(products);
} catch (err) {
console.log(err);
}
}
}
Initiating a Purchase
Your app can display the purchase screen through the createPurchaseIntent API.
Call createPurchaseIntent with required parameter. Parameter is an object includes productId, priceType and developerPayload. If parameters are correct it automatically brings the checkout page. If a problem occurs the createPurchaseIntent API will return a Status object describing the error.
Code:
import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private iap: HMSInAppPurchases) {}
ngOnInit() {
...
}
createPurchaseIntent = async (product) => {
try {
let message = await this.iap.createPurchaseIntent({
priceType: product.priceType,
productId: product.productId,
developerPayload: DEVELOPERPAYLOAD
});
if (message.returnCode === 0) {// if successful
console.log(message);
} else {
alert('Purchase was not successful.');
console.log(message);
}
} catch (err) {
console.log(err);
}
}
}
Auto-renewable Subscriptions
Users can purchase access to value-added functions or content in a specified period of time. The subscriptions are automatically renewed on a recurring basis until users decide to cancel.
You can use the createPurchaseIntent API like the example above to display the subscription purchase page. HMS IAP Plugin provides startIapActivity API to display subscription management and subscription editing pages.
Simply call the startIapActivity API to display the subscription management page. If you want to display display the subscription editing page you just need to pass the ID of the product as a parameter.
Code:
import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private iap: HMSInAppPurchases) {}
async ngOnInit() {
...
}
editSubscription = (product_id) => {
this.iap.startIapActivity(product_id).then(() => {
console.log('Subscription editing page is displayed');
}).catch(error => {
console.log(error);
})
}
manageSubscriptions = () => {
this.iap.startIapActivity().then(() => {
console.log('Subscription management page is displayed');
}).catch(error => {
console.log(error);
});
}
}
In this article, I tried to explain to you the use of the In-App Purchases Cordova Plugin through code examples.

A Novice Journey of Integrating Site Kit into Ionic Application

Introduction
HMS Site Kit allow us to search places and in return provides variety of information such as address, location, phone number etc. We can search for places either by proximity or a text string. Our app can provide users with convenient and secure access to diverse, place-related services, and therefore acquire more users.
HMS Site Kit Services
1. Place Search
2. Nearby Place Search
3. Place Details
4. Place Search Suggestion
5. Widget Search
In this article we will focus on Place Search, Nearby Place Search, Place Search Suggestion and Widget Search provided by HMS Site Kit.
Ionic Framework
Ionic Framework is an open source UI toolkit for building performant, high-quality mobile and desktop apps using web technologies such as HTML, CSS, and JavaScript with integrations for popular frameworks like Angular and React.
Think of Ionic as the front-end UI framework that handles all of the look and feel and UI interactions your app needs in order to be compelling. Unlike a responsive framework, Ionic comes with very native-styled mobile UI elements and layouts that you’d get with a native SDK on Android or iOS but didn’t really exist before on the web.
Since Ionic is an HTML5 framework, it needs a native wrapper like Cordova or Capacitor in order to run as a native app.
Here we will use Ionic framework with Angular and Capacitor as native wrapper.
Demo
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4) Must install node in the system
5) Must install Ionic in the system using below command:
Code:
npm install -g [user=1329689]@iONiC[/user]/cli
Things need to be done
1) Generating a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
2) Create an app in the Huawei AppGallery connect and enable ML Kit in Manage API section.
3) Provide the SHA Key in App Information Section.
4) Provide storage location.
5) Download the agconnect-services.json and store it somewhere on our computer.
6) Create a blank Ionic Project using below command:
Code:
ionic start Your_Application_Name blank --type=angular
7) Download the Cordova Site Kit Plugin. Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install <CORDOVA_SITE_KIT_PLUGIN_PATH>
8) If you want full Ionic support with code completion etc., install @iONiC-native/core in your project.
Code:
npm install [user=1329689]@iONiC[/user]-native/core --save-dev
9) Run the following command to copy the "ionic/dist/hms-ml" folder from library to "node_modules @iONiC-native" folder under your Ionic project.
Code:
cp node_modules/@hmscore/cordova-plugin-hms-ml/ionic/dist/hms-ml node_modules [user=1329689]@iONiC[/user]-native/ -r
10) Run the following command to compile the project:
Code:
ionic build
npx cap init [appName] [appId]
Where appName is the name of your app, and appId is package_name in your agconnect-services.json file (example: com.example.app).
11) Run the following command to add android platform to your project:
Code:
ionic capacitor add android
12) Make sure your project has a build.gradle file with a maven repository address and agconnect service dependencies as shown below:
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.google.gms:google-services:4.3.3'
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
Code:
android {
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "YOUR_PACKAGE_NAME"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
storeFile file("mykeystore.jks") // Signing certificate.
storePassword "XXXXXX" // KeyStore password.
keyAlias "XXXXXX" // Alias.
keyPassword "XXXXXX" // Key password.
v1SigningEnabled true
v2SigningEnabled true
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.release
debuggable true
}
}
}<img src="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20201016091920.80521901239093620186278348845525:50511111010449:2800:68B931001F4C6BCA4A0671802459A06AA748D35EF1BA25865E9BE8C4A629C3FE.png" style="color: rgb(51,51,51);font-family: "Times New Roman" , serif;font-size: 21.0px;white-space: normal;width: 1.0px;height: 1.0px;">
14) Add plugin to the build.gradle file in the app directory as show below:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
15) Add ads service implementation into to dependencies section of build.gradle file in the app directory as show below:
Code:
dependencies {
…
implementation 'com.huawei.hms:site:5.0.0.300'
}
16) Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below:
17) To update dependencies, and copy any web assets to your project, run the following code:
Code:
npx capacitor sync
Let's Code
Avoid No Provider Error
To avoid No Provider Error, we need to add FileChooser, Android Permission and HMS ML kit in app.module.ts providers section and also make sure to import the same as shown below:
Code:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from [user=1329689]@iONiC[/user]/angular';
import { SplashScreen } from [user=1329689]@iONiC[/user]-native/splash-screen/ngx';
import { StatusBar } from [user=1329689]@iONiC[/user]-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HmsSite } from [user=1329689]@iONiC[/user]-native/hms-site/ngx'
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
HmsSite,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Create page in Ionic
Run the following command to create page in Ionic project:
Code:
Ionic generate page page-name
Import
Import the following code in your home.page.ts :
Code:
import { Component, IterableDiffers } from '@angular/core';
import { HmsSite } from [user=1329689]@iONiC[/user]-native/hms-site/ngx';
Initializing the service
First we need to initialize the service. In order to that we need to call the initializeService method to initialize the HMS Site Kit service using our project API key. The API key can be found in our agconnect-services.json file.
Code:
constructor(private hmssite: HmsSite) {
var config = {
apiKey: "YOUR_API_KEY"
};
hmssite.initializeService(
config
);
}
Place Search
Basically it helps us to extract information of a particular place like tourist attraction, enterprises and school by specifying keywords, coordinates and other information.
Code:
public async onTextSearch() {
let textSearchReq = {
query: this.textSearchPlaces,
location: {
lat: 20.5937,
lng: 78.9629,
},
radius: 5000,
poiType: this.hmssite.LocationType.ADDRESS,
countryCode: "IN",
language: "en",
pageIndex: 1,
pageSize: 5
};
try {
var res = JSON.parse(JSON.stringify(await this.hmssite.textSearch(textSearchReq)));
this.data = JSON.stringify(JSON.parse(JSON.stringify(res)).sites);
this.result.length = 0;
for (var i = 0; i < JSON.parse(this.data).length; i++) {
var text: any = {
"NAME": JSON.stringify(JSON.parse(this.data)[i].name),
"ADDRESS": JSON.stringify(JSON.parse(this.data)[i].address),
"DISTANCE": JSON.stringify(JSON.parse(this.data)[i].distance),
"LOCATION": JSON.stringify(JSON.parse(this.data)[i].location),
"POIDETAILS": JSON.stringify(JSON.parse(this.data)[i].poi),
"RATING": JSON.stringify(JSON.parse(this.data)[i].rating),
"SITEID": JSON.stringify(JSON.parse(this.data)[i].siteId)
};
this.result.push(text)
}
}
catch (ex) {
alert(JSON.stringify(ex))
}
}
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0203394385930860028&channelname=HuoDong59&ha_source=xda
Well explained, can we restrict area when we are searching data.
Thank you very much

Intermediate: How to Integrate Location Kit into Hotel booking application

Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article, I am going to implement HMS Location Kit & Shared Preferences.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect.
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Location Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Important: While adding app, the package name you enter should be the same as your Flutter project’s package name.
Note: Before you download agconnect-services.json file, make sure the required kits are enabled.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
Code:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<application ...
</manifest>
3. Refer below URL for cross-platform plugins. Download required plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001050304074-V1
4. After completing all the steps above, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_location:
path: ../huawei_location/
flutter:
uses-material-design: true
assets:
- assets/images/
5. After adding them, run flutter pub get command. Now all the plugins are ready to use.
6. Open main.dart file to create UI and business logics.
Location kit
HUAWEI Location Kit assists developers in enabling their apps to get quick and accurate user locations and expand global positioning capabilities using GPS, Wi-Fi, and base station locations.
Fused location: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data.
Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behaviour.
Geofence: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs.
Integration
Permissions
First of all we need permissions to access location and physical data.
Create a PermissionHandler instance,add initState() for initialize.
Code:
final PermissionHandler permissionHandler;
@override
void initState() {
permissionHandler = PermissionHandler(); super.initState();
}
Check Permissions
We need to check device has permission or not using hasLocationPermission() method.
Code:
void hasPermission() async {
try {
final bool status = await permissionHandler.hasLocationPermission();
if(status == true){
showToast("Has permission: $status");
}else{
requestPermission();
}
} on PlatformException catch (e) {
showToast(e.toString());
}
}
If device don’t have permission,then request for Permission to use requestLocationPermission() method.
Code:
void requestPermission() async {
try {
final bool status = await permissionHandler.requestLocationPermission();
showToast("Is permission granted");
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Fused Location
Create FusedLocationPrvoiderClient instance using the init() method and use the instance to call location APIs.
Code:
final FusedLocationProviderClient locationService
@override
void initState() {
locationService = FusedLocationProviderClient(); super.initState();
}
getLastLocation()
Code:
void getLastLocation() async {
try {
Location location = await locationService.getLastLocation();
setState(() {
lastlocation = location.toString();
print("print: " + lastlocation);
});
} catch (e) {
setState(() {
print("error: " + e.toString());
});
}
}
getLastLocationWithAddress()
Create LocationRequest instance and set required parameters.
Code:
final LocationRequest locationRequest;
locationRequest = LocationRequest()
..needAddress = true
..interval = 5000;
void _getLastLocationWithAddress() async {
try {
HWLocation location =
await locationService.getLastLocationWithAddress(locationRequest);
setState(() {
String street = location.street;
String city = location.city;
String countryname = location.countryName;
currentAddress = '$street' + ',' + '$city' + ' , ' + '$countryname';
print("res: $location");
});
showToast(currentAddress);
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Location Update using Call back
Create LocationCallback instance and create callback functions in initstate().
Code:
LocationCallback locationCallback;
@override
void initState() {
locationCallback = LocationCallback(
onLocationResult: _onCallbackResult,
onLocationAvailability: _onCallbackResult,
);
super.initState();
}
void requestLocationUpdatesCallback() async {
if (_callbackId == null) {
try {
final int callbackId = await locationService.requestLocationUpdatesExCb(
locationRequest, locationCallback);
_callbackId = callbackId;
} on PlatformException catch (e) {
showToast(e.toString());
}
} else {
showToast("Already requested location updates.");
}
}
void onCallbackResult(result) {
print(result.toString());
showToast(result.toString());
}
I have created Helper class to store user login information in locally using shared Preferences class.
Code:
class StorageUtil {
static StorageUtil _storageUtil;
static SharedPreferences _preferences;
static Future<StorageUtil> getInstance() async {
if (_storageUtil == null) {
var secureStorage = StorageUtil._();
await secureStorage._init();
_storageUtil = secureStorage;
}
return _storageUtil;
}
StorageUtil._();
Future _init() async {
_preferences = await SharedPreferences.getInstance();
}
// get string
static String getString(String key) {
if (_preferences == null) return null;
String result = _preferences.getString(key) ?? null;
print('result,$result');
return result;
}
// put string
static Future<void> putString(String key, String value) {
if (_preferences == null) return null;
print('result $value');
return _preferences.setString(key, value);
}
}
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. To work with mock location we need to add permissions in Manifest.XML.
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Location kit in this article. We have learned how to get Lastlocation, getLocationWithAddress and how to use callback method, in flutter how to store data into Shared Preferences in applications.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Location Kit URL
Shared Preferences URL
Read full article
Goodjob
Thank you
I thought huawei doesn't support flutter. I guess it should as it is Android only.
good
Wow
Nice.
I thought its not doable
Interesting.
Like

Intermediate: Site kit Search Capabilities in Food DeliveryApp in Flutter – Part 2

Introduction
In this article, we will be integrating other Search features of Site kit, you can find previous article here, and Huawei Site Kit provides core capabilities to developer to quickly build apps with which users can explore world around them seamlessly. Huawei Site kit provides following Search capabilities to developer as shown below.
Keyword search: returns the place list based on the keywords entered by user.
Nearby place search: Searches for nearby location based on current location of the user’s device.
Place detail search: Search for details about the place.
Place search suggestion: Returns list of suggested places.
Autocomplete: Returns an autocomplete place and a list of suggested places based on the entered keyword.
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARES_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: sample_one
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_map:
path: ../huawei_map/
huawei_location:
path: ../huawei_location/
huawei_safetydetect:
path: ../huawei_safetydetect
huawei_site:
path: ../huawei_site
http: ^0.12.2
rflutter_alert: ^2.0.2
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
# add this line to your dependencies
toast: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
Declare and instantiate service object
Code:
Future<void> initmySearchService() async {
searchService = await SearchService.create(Uri.encodeComponent(API_KEY));
}<strong> </strong>
How to I call QueryAutoCompleteRequest api ?
Code:
void autocomplete(String value) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
// Create QueryAutocompleteRequest and its body.
QueryAutocompleteRequest request = QueryAutocompleteRequest(query: value);
// Create QueryAutocompleteResponse object.
// Call queryAutocomplete() method.
// Assign the results.
QueryAutocompleteResponse response =
await searchService.queryAutocomplete(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
locations.clear();
entries.clear();
for (String key in data.keys) {
if (key == 'sites') {
data2 = data[key];
for (var element in data2) {
setState(() {
entries.add(element['name'] + "\n" + element['formatAddress']);
locations.add(new LatLng(
element['location']['lat'], element['location']['lng']));
});
}
}
}
}
}
How to I call QuerySuggestionRequest api ?
Code:
void querySuggestionSearch(String value) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
QuerySuggestionRequest request = QuerySuggestionRequest();
request.query = value;
request.location = Coordinate(lat: 12.893478, lng: 77.334595);
request.language = "en";
request.countryCode = "IN";
request.radius = 5000;
// Create QuerySuggestionResponse object.
// Call querySuggestion() method.
// Assign the results.
QuerySuggestionResponse response =
await searchService.querySuggestion(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
entries.clear();
for (String key in data.keys) {
if (key == 'sites') {
data2 = data[key];
for (var element in data2) {
setState(() {
entries.add(element['name'] + "\n" + element['formatAddress']);
locations.add(new LatLng(
element['location']['lat'], element['location']['lng']));
});
}
}
}
}
}
How to I call DetailSearchRequest api ?
Code:
void placeDetailSearch(String siteId) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
DetailSearchRequest request = DetailSearchRequest();
request.siteId = siteId;
request.language = "en";
// Create DetailSearchResponse object.
// Call detailSearch() method.
// Assign the results.
DetailSearchResponse response = await searchService.detailSearch(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
setState(() {
result = data['site'].toString();
});
} else {
print("Response is NULL");
}
}
Result
Note: Place detail search takes sit id as input and gives site information as result.
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path in yaml.
Make sure that plugin unzipped in parent directoryof project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in Ag-connect.
Conclusion
In this article, we have learnt how to integrate Huawei Site kit Search capabilities for DeliveryApp in flutter. Where user can search for specific hotel or restaurants in the search box and clicks on the result to find the list of orders. Similar way you can use Huawei Site kit as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei Site kit Search capabilities in flutter.
Reference
Site kit
Site kit plugin
Original Source

Intermediate: Integration of Huawei Ads with Game Services in Flutter (Cross platform)

Introduction
In this article, we will be integrating Huawei Ads and Game Services kit in flutter application. You can access to range of development capabilities. You can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login game with Huawei IDs. You can also use the service to quickly implement achievements, game events, and game addiction prevention functions and perform in-depth game operations based on user and content localization. Huawei Ads kit helps developer to monetize application.
Huawei supports following Ads types
Banner
Interstitial
Native
Reward
Splash
Instream(Roll)
Huawei Game Services Capabilities
Game Login
Achievements
Floating window*
Game Addiction prevention*
Events
Leaderboards
Save Games*
Player statistics*
Access to Basic Game Information*
Note: Restricted to regions (*)
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone with API 4.x.x or above (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project.
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies.
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: gameservice234demo
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_account:
path: ../huawei_account
huawei_gameservice:
path: ../huawei_gameservice
huawei_ads:
path: ../huawei_ads_301
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
How do I launch or initialize the Ads SDK?
Code:
HwAds.init();
How do I load Splash Ads?
Code:
void showSplashAd() {
SplashAd _splashAd = createSplashAd();
_splashAd
..loadAd(
adSlotId: "testq6zq98hecj",
orientation: SplashAdOrientation.portrait,
adParam: AdParam(),
topMargin: 20);
Future.delayed(Duration(seconds: 7), () {
_splashAd.destroy();
});
}
static SplashAd createSplashAd() {
SplashAd _splashAd = new SplashAd(
adType: SplashAdType.above,
ownerText: ' Huawei SplashAd',
footerText: 'Test SplashAd',
); // Splash Ad
return _splashAd;
}
How do I load Native Ad?
Code:
static NativeAd createNativeAd() {
NativeStyles stylesSmall = NativeStyles();
stylesSmall.setCallToAction(fontSize: 8);
stylesSmall.setFlag(fontSize: 10);
stylesSmall.setSource(fontSize: 11);
NativeAdConfiguration configuration = NativeAdConfiguration();
configuration.choicesPosition = NativeAdChoicesPosition.topLeft;
return NativeAd(
// Your ad slot id
adSlotId: "testu7m3hc4gvm",
controller: NativeAdController(
adConfiguration: configuration,
listener: (AdEvent event, {int? errorCode}) {
print("Native Ad event : $event");
}),
type: NativeAdType.small,
styles: stylesSmall,
);
}
How do I load Interstitial Ad?
Code:
void showInterstitialAd() {
InterstitialAd interstitialAd =
InterstitialAd(adSlotId: "teste9ih9j0rc3", adParam: AdParam());
interstitialAd.setAdListener = (AdEvent event, {int? errorCode}) {
print("InterstitialAd event : $event");
};
interstitialAd.loadAd();
interstitialAd.show();
}
How do I load Rewarded Ad?
Code:
static Future<void> showRewardAd() async {
RewardAd rewardAd = RewardAd();
await rewardAd.loadAd(
adSlotId: "testx9dtjwj8hp",
adParam: AdParam(),
);
rewardAd.show();
rewardAd.setRewardAdListener =
(RewardAdEvent event, {Reward? reward, int? errorCode}) {
print("RewardAd event : $event");
if (event == RewardAdEvent.rewarded) {
print('Received reward : ${reward!.toJson().toString()}');
}
};
}
How do I launch or initialize the game?
Code:
void init() async {
await JosAppsClient.init();
}
Use Huawei ID for login
Code:
Future<void> login() async {
helper = new HmsAuthParamHelper()
..setIdToken()
..setAccessToken()
..setAuthorizationCode()
..setEmail()
..setProfile();
huaweiId = await HmsAuthService.signIn(authParamHelper: helper);
if (huaweiId != null) {
setState(() {
isLoggedIn = true;
msg = huaweiId!.displayName;
loginLabel = "Logged in as";
print(msg);
});
getPlayer();
} else {
setState(() {
msg = " Inside else ";
});
}
}
How do I get Achievements list?
Code:
Future<void> getAchievements() async {
try {
List<Achievement> result =
await AchievementClient.getAchievementList(true);
print("Achievement:" + result.toString());
} on PlatformException catch (e) {
print("Error on getAchievementList API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I displaying the Achievements List Page of HUAWEI AppAssistant using Intent?
Code:
void showAchievementsIntent() {
try {
AchievementClient.showAchievementListIntent();
} on PlatformException catch (e) {
print("Error on showAchievementListIntent API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I call Floating window?
Code:
try {
await BuoyClient.showFloatWindow();
} on PlatformException catch (e) {
print("Error on showFloatWindow API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I get All Events?
Code:
Future<void> getEvents() async {
try {
List<GameEvent> result = await EventsClient.getEventList(true);
print("Events: " + result.toString());
} on PlatformException catch (e) {
print("Error on getEventList API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I submit an Event?
Code:
Future<void> sendEvent(String eventId) async {
try {
await EventsClient.grow(eventId, 1);
print("************** Event sent **************");
} on PlatformException catch (e) {
print("Error on grow API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
How do I get All Leaderboard data?
Code:
Future<void> getLeaderboardList() async {
// check the leaderboard status
int result = await RankingClient.getRankingSwitchStatus();
// set leaderboard status
int result2 = await RankingClient.setRankingSwitchStatus(1);
List<Ranking> rankings = await RankingClient.getAllRankingSummaries(true);
print(rankings);
//To show RankingIntent
RankingClient.showTotalRankingsIntent();
}
How do I submit the ranking score?
Code:
try {
int score = 102;
RankingClient.submitRankingScores(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitRankingScores API, Error: ${e.code}, Error Description:${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
Or
try {
int score = 125;
ScoreSubmissionInfo result = await RankingClient.submitScoreWithResult(rankingId, score);
} on PlatformException catch (e) {
print("Error on submitScoreWithResult API, Error: ${e.code}, Error Description: ${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
How do I displaying the Leaderboard List Page of HUAWEI AppAssistant using Intent?
Code:
void showLeaderboardIntent() {
try {
RankingClient.showTotalRankingsIntent();
} on PlatformException catch (e) {
print("Error on showLeaderboardListIntent API, Error: ${e.code}, Error Description:
${GameServiceResultCodes.getStatusCodeMessage(e.code)}");
}
}
Result
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path Ads in yaml.
Make sure that plugin unzipped in parent directory of project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in ag-connect.
Game Services previous article you can check out here
Conclusion
In this article, we have learnt how to integrate capabilities of Huawei Ads with Game Services kit in flutter application. You can promote your game quickly and more efficiently to Huawei’s vast users as Huawei Game Services allows users to login with Huawei IDs and this can be achieved by implementing its capabilities in your application. Developer can easily integrate and monetize the application which helps developer to grow financial long with application. Similar way you can use Huawei Ads with Game Services as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei Ads with Game Services capabilities in flutter.
Reference
GameServices Kit
Plutter Plugin Game services
Ads Kit
Original Source

Categories

Resources