{
"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.
Related
This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
This is all about integration of HMS Safety Detect API in the Android app using MVVM RxAndroid.
What is HMS Safety Detect API?
Ø The Safety Detect provides system integrity check (SysIntegrity), app security check (AppsCheck), malicious URL check (URLCheck), and fake user detection (UserDetect), helping you prevent security threats to your app.
{
"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"
}
Let’s create a Demo Project:
HUAWEI HMS Safety Detect integration requires the following preparations
Ø Creating an AGC Application.
Ø Creating an Android Studio Project.
Ø Generating a signature certificate.
Ø Generating a signature certificate fingerprint.
Ø Configuring the signature certificate fingerprint.
Ø Adding the application package name and save the configuration file.
Ø Configure the Maven address and AGC gradle plug-in.
Ø Configure the signature file in Android Studio.
In this article, we will implement SysIntegrity API in demo project using with RxAndroid and MVVM.
Call the API and handle responses.
Verify the certificate chain, signature, and domain name on the server.
1. Open AppGallery Console:
1. We need to create an application inside console.
2. We need to enable the Safety Detect api.
Go to Console > AppGallery Connect > My apps, click your app, and go to Develop > Manage APIs.
Now enable Safety Detect Api
Download the agconnect-services.json
Move the downloaded agconnect-services.json file to the app root directory of your Android Studio project.
We need to add HMS SDK dependency in app:gradle file
Code:
implementation 'com.huawei.hms:safetydetect:4.0.0.300'
We need to add maven dependency inside project:gradle file
Code:
maven { url 'http://developer.huawei.com/repo/' }
We need to add two more dependencies in app:gradle file
Code:
// MVVM
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
// RxAndroid
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Enable Data Binding
Code:
dataBinding {
enabled = true
}
2. Let’s implement api :
I have created following classes.
1. SysIntegrityDataSource : Which invoke the System Integrity Api with help of RxJava.
2. SysIntegrityViewModel : Which handle the response from System Integrity api and provide LiveData for view componets.
3. SysIntegrityFragment : Which observe the livedata from viewmodel class and set values in views such as textviews and button.
Note: If you are not familiar with MVVM or RxAndroid then I would like to suggest you to please go through my following articles:
· Android MyShows App — Rxandroid MVVM LiveData ViewModel DataBinding, Networking with Retrofit, Gson & Glide — Series
· Demystifying Data Binding — Android Jetpack — Series
Let’s see the implementation of SysIntegrityDataSource.java class.
Code:
public class SysIntegrityDataSource {
private static final String APP_ID = "XXXXXXXX";
private Context context;
public SysIntegrityDataSource(Context context) {
this.context = context;
}
public Single<SysIntegrityResp> executeSystemIntegrity() {
return Single.create(this::invokeSysIntegrity);
}
private void invokeSysIntegrity(SingleEmitter<SysIntegrityResp> emitter) {
byte[] nonce = ("Sample" + System.currentTimeMillis()).getBytes();
SafetyDetect.getClient(context)
.sysIntegrity(nonce, APP_ID)
.addOnSuccessListener(emitter::onSuccess)
.addOnFailureListener(emitter::onError);
}
}
invokeSysIntegrity() : This method invoke the System Integrity api and emit the data onSuccess/OnError and past it to Single<SysIntegrityResp> observable.
executeSystemIntegrity() : This method will create Single observable and return the response from invokeSysIntegrity() method.
3. Let’s implement ViewModel :
I have created SysIntegrityViewModel.java class.
Code:
public class SysIntegrityViewModel extends AndroidViewModel {
private final CompositeDisposable disposables = new CompositeDisposable();
private SysIntegrityDataSource sysIntegrityDataSource;
private MutableLiveData<SysIntegrityResp> systemIntegrityLiveData;
private MutableLiveData<String> error;
public SysIntegrityViewModel(Application app) {
super(app);
sysIntegrityDataSource = new SysIntegrityDataSource(app.getBaseContext());
systemIntegrityLiveData = new MutableLiveData<>();
error = new MutableLiveData<>();
}
public LiveData<SysIntegrityResp> observerSystemIntegrity() {
sysIntegrityDataSource.executeSystemIntegrity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<SysIntegrityResp>() {
@Override
public void onSubscribe(Disposable d) {
disposables.add(d);
}
@Override
public void onSuccess(SysIntegrityResp response) {
systemIntegrityLiveData.setValue(response);
}
@Override
public void onError(Throwable e) {
error.setValue(e.getMessage());
}
});
return systemIntegrityLiveData;
}
public LiveData<String> getError() {
return error;
}
@Override
protected void onCleared() {
disposables.clear();
}
}
MutableLiveData<SysIntegrityResp> systemintegrityLiveData: This field which provide the live data and return the value from viewmodel to fragment class.
observerSysIntegrity() : Which observe RxAndroid’s Single(observable) on main thread and set the value in systemIntegrityLiveData. If we got error while observing it will post the error in MutableLiveData<String> error.
4. Let’s implement Fragment :
I have created SysIntegrityFragment.java class Which obaserve the System Integrity api’s reponse and set the values in views.
Code:
public class SysIntegrityFragment extends Fragment {
private SysIntegrityViewModel sysIntegrityViewModel;
private FragmentSysBinding sysBinding;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
sysBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_sys, container, false);
sysIntegrityViewModel = ViewModelProviders.of(this).get(SysIntegrityViewModel.class);
sysBinding.btnSys.setOnClickListener(v->{
processView();
sysIntegrityViewModel.observerSystemIntegrity().observe(getViewLifecycleOwner(), this::setSystemIntegrity);
sysIntegrityViewModel.getError().observe(getViewLifecycleOwner(),this::showError);
});
return sysBinding.getRoot();
}
private void setSystemIntegrity(SysIntegrityResp response){
String jwsStr = response.getResult();
String[] jwsSplit = jwsStr.split("\\.");
String jwsPayloadStr = jwsSplit[1];
String payloadDetail = new String(Base64.decode(jwsPayloadStr.getBytes(), Base64.URL_SAFE));
try {
final JSONObject jsonObject = new JSONObject(payloadDetail);
final boolean basicIntegrity = jsonObject.getBoolean("basicIntegrity");
sysBinding.btnSys.setBackgroundResource(basicIntegrity ? R.drawable.btn_round_green : R.drawable.btn_round_red);
sysBinding.btnSys.setText(R.string.rerun);
String isBasicIntegrity = String.valueOf(basicIntegrity);
String basicIntegrityResult = "Basic Integrity: " + isBasicIntegrity;
sysBinding.txtBasicIntegrityTitle.setText(basicIntegrityResult);
if (!basicIntegrity) {
String advice = "Advice: " + jsonObject.getString("advice");
sysBinding.txtPayloadAdvice.setText(advice);
}
} catch (JSONException e) {
}
}
private void showError(String error){
Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_SHORT).show();
sysBinding.btnSys.setBackgroundResource(R.drawable.btn_round_yellow);
sysBinding.btnSys.setText(R.string.rerun);
}
private void processView() {
sysBinding.txtBasicIntegrityTitle.setText("");
sysBinding.txtPayloadBasicIntegrity.setText("");
sysBinding.btnSys.setText(R.string.processing);
sysBinding.btnSys.setBackgroundResource(R.drawable.btn_round_processing);
}
}
We have instantiated instance of view model using ViewModel factory method.
We will consume the response on button click’s event.
If we got success response then we will display inside textviews and button otherwise we will show the error toast.
5. Let’s see the result:
Build the app and hit run button.
Click > RunDetection Case 1: Success Case 2: SDK Error Case 3: Integrity false (Rooted)
I hope you have learnt something new today. If you have any query regarding this article, please feel free to post any comments.
Any questions about this, you can try to acquire answers from HUAWEI Developer Forum.
Useful sharing,thanks
Thank you so much for sharing, very useful.
Thank you so much for sharing, very useful.
Thank you so much for sharing, very useful.
Does it work offline?
useful sharing,thanks!
More information like this, you can visit HUAWEI Developer Forum
Introduction
This article covers, how to integrate React Native HMS ML Kit to a React Native application.
React Native Hms ML Kit supports services listed below
· Text Related Services
· Language Related Services
· Image Related Services
· Face/Body Related Services
There are several number of uses cases of these services, you can combine them or just use them to create different functionalities in your app. For basic understanding, please read uses cases from here.
Github: https://github.com/HMS-Core/hms-react-native-plugin/tree/master/react-native-hms-ml
Prerequisites
Step 1
Prepare your development environment using this guide.
After reading this guide you should have React Native Development Environment setted up, Hms Core (APK) installed and Android Sdk installed.
Step 2
Configure your app information in App Gallery by following this guide.
After reading this guide you should have a Huawei Developer Account, an App Gallery app, a keystore file and enabled ml kit service from AppGallery.
Integrating React Native Hms ML Kit
Warning : Please make sure that, prerequisites part successfully completed.
Step 1
Code:
npm i @hmscore/react-native-hms-ml
Step 2
Open build.gradle file in project-dir > android folder.
Go to buildscript > repositories and allprojects > repositories, and configure the Maven repository address.
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
Go to buildscript > dependencies and add dependency configurations.
Code:
buildscript {
dependencies {
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
}
}
Step 3
Open build.gradle file which is located under project.dir > android > app directory.
Add the AppGallery Connect plug-in dependency to the file header.
Code:
apply plugin: 'com.huawei.agconnect'
The apply plugin: ‘com.huawei.agconnect’ configuration must be added after the apply plugin: ‘com.android.application’ configuration.
The minimum Android API level (minSdkVersion) required for ML Kit is 19.
Configure build dependencies of your project.
Code:
dependencies {
...
implementation 'com.huawei.agconnect:agconnect-core:1.0.0.301'
}
Now you can use React Native Hms ML and import modules like below code.
Code:
import {<module_name>} from '@hmscore/react-native-hms-ml';
Lets Create An Application
We have already created an application in prerequisites section.
Our app will be about recognizing text in images and converting it to speech. So, we will use HmsTextRecognitionLocal, HmsFrame and HmsTextToSpeech modules. We will select images by using react-native-image-picker, so don’t forget to install it.
Note That : Before running this code snippet please check for your app permissions.
Step 1
We need to add some settings before using react-native-image-picker to AndroidManifest.xml.
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
...
android:requestLegacyExternalStorage="true">
Step 2
Code:
import React from 'react';
import { Text, View, ScrollView, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
import { HmsTextRecognitionLocal, HmsFrame, HmsTextToSpeech, NativeEventEmitter } from '@hmscore/react-native-hms-ml';
import ImagePicker from 'react-native-image-picker';
const options = {
title: 'Choose Method',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
const styles = StyleSheet.create({
bg: { backgroundColor: '#eee' },
customEditBox: {
height: 450,
borderColor: 'gray',
borderWidth: 2,
width: "95%",
alignSelf: "center",
marginTop: 10,
backgroundColor: "#fff",
color: "#000"
},
buttonTts: {
width: '95%',
height: 70,
alignSelf: "center",
marginTop: 35,
},
startButton: {
paddingTop: 10,
paddingBottom: 10,
backgroundColor: 'white',
borderRadius: 10,
borderWidth: 1,
borderColor: '#888',
backgroundColor: '#42aaf5',
},
startButtonLabel: {
fontWeight: 'bold',
color: '#fff',
textAlign: 'center',
paddingLeft: 10,
paddingRight: 10,
},
});
export default class App extends React.Component {
// create your states
// for keeping imageUri and recognition result
constructor(props) {
super(props);
this.state = {
imageUri: '',
result: '',
};
}
// this is a key function in Ml Kit
// It sets the frame for you and keeps it until you set a new one
async setMLFrame() {
try {
var result = await HmsFrame.fromBitmap(this.state.imageUri);
console.log(result);
} catch (e) {
console.error(e);
}
}
// this creates text recognition settings by default options given below
// languageCode : default is "rm"
// OCRMode : default is OCR_DETECT_MODE
async createTextSettings() {
try {
var result = await HmsTextRecognitionLocal.create({});
console.log(result);
} catch (e) {
console.error(e);
}
}
// this function calls analyze function and sets the results to state
// The parameter false means we don't want a block result
// If you want to see results as blocks you can set it to true
async analyze() {
try {
var result = await HmsTextRecognitionLocal.analyze(false);
this.setState({ result: result });
} catch (e) {
console.error(e);
}
}
// this function calls close function to stop recognizer
async close() {
try {
var result = await HmsTextRecognitionLocal.close();
console.log(result);
} catch (e) {
console.error(e);
}
}
// standart image picker operation
// sets imageUri to state
// calls startAnalyze function
showImagePicker() {
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
this.setState({
imageUri: response.uri,
});
this.startAnalyze();
}
});
}
// configure tts engine by giving custom parameters
async configuration() {
try {
var result = await HmsTextToSpeech.configure({
"volume": 1.0,
"speed": 1.0,
"language": HmsTextToSpeech.TTS_EN_US,
"person": HmsTextToSpeech.TTS_SPEAKER_FEMALE_EN
});
console.log(result);
} catch (e) {
console.error(e);
}
}
// create Tts engine by call
async engineCreation() {
try {
var result = await HmsTextToSpeech.createEngine();
console.log(result);
} catch (e) {
console.error(e);
}
}
// set Tts callback
async callback() {
try {
var result = await HmsTextToSpeech.setTtsCallback();
console.log(result);
} catch (e) {
console.error(e);
}
}
// start speech
async speak(word) {
try {
var result = await HmsTextToSpeech.speak(word, HmsTextToSpeech.QUEUE_FLUSH);
console.log(result);
} catch (e) {
console.error(e);
}
}
// stop engine
async stop() {
try {
var result = await HmsTextToSpeech.stop();
console.log(result);
} catch (e) {
console.error(e);
}
}
// manage functions in order
startAnalyze() {
this.setState({
result: 'processing...',
}, () => {
this.createTextSettings()
.then(() => this.setMLFrame())
.then(() => this.analyze())
.then(() => this.close())
.then(() => this.configuration())
.then(() => this.engineCreation())
.then(() => this.callback())
.then(() => this.speak(this.state.result));
});
}
render() {
return (
<ScrollView style={styles.bg}>
<TextInput
style={styles.customEditBox}
value={this.state.result}
placeholder="Text Recognition Result"
multiline={true}
editable={false}
/>
<View style={styles.buttonTts}>
<TouchableOpacity
style={styles.startButton}
onPress={this.showImagePicker.bind(this)}
underlayColor="#fff">
<Text style={styles.startButtonLabel}> Start Analyze </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
Test the App
· First write “Hello World” on a blank paper.
· Then run the application.
· Press “Start Analyze” button and take photo of your paper.
· Wait for the result.
· Here it comes. You will see “Hello World” on screen and you will hear it from your phone.
{
"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"
}
Conclusion
In this article, we integrated and used React Native Hms ML Kit to our application.
From: https://medium.com/huawei-developers/react-native-hms-ml-kit-installation-and-example-242dc83e0941
Is there any advantage in Huawei ML kit compare to others .
Introduction
HUAWEI In-App Purchases (IAP) aggregates multiple payment methods for global payments, and can be easily integrated into your app to help revenue increase. Users can purchase a variety of products or services, including common virtual products and subscriptions and directly within your app. For details, please refer to HUAWEI IAP 5.0.
First you need to understand three types of in-app products supported by HUAWEI In-App Purchases.
1. Consumable: Consumables are used once, are depleted, and can be purchased again.
Example: Extra lives and gems in a game
2. Non-consumable: Non-consumables are purchased once and do not expire.
Example: Extra game levels in a game or permanent membership of an app
3. 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.
Example: Non-permanent membership of an app, such as a monthly video membership
For details, refer to
https://www.b4x.com/b4a.html
Follow all the steps mentioned in Basic Setup to start HMS integration on B4A Platform.
Refer to
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201286424114350051&fid=0101246461018590361
Enable In-App Purchases in App gallery connect.
{
"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"
}
Tips & Tricks:
Before enable In-App Purchases create marchant account. It will take two days to approve then only we can enable In-App Purchases in AppGallery Connect.
Creating Wrapper Class
1. Downloading the AAR Packages and JSON File
Sign in to HUAWEI Developer and download the AAR packages required.
AAR packages related to HMS In-App Purchases kit, as follows.
HMSSDK Agconnect-Core:
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-core/1.4.0.300/agconnect-core-1.4.0.300.aar
HMSSDK Tasks:
https://developer.huawei.com/repo/com/huawei/hmf/tasks/1.4.1.300/tasks-1.4.1.300.aar
HMSSDK Available Update:
https://developer.huawei.com/repo/com/huawei/hms/availableupdate/5.0.0.301/availableupdate-5.0.0.301.aar
HMSSDK Base:
https://developer.huawei.com/repo/com/huawei/hms/base/5.0.0.301/base-5.0.0.301.aar
HMSSDK Device:
https://developer.huawei.com/repo/com/huawei/hms/device/5.0.0.301/device-5.0.0.301.aar
HMSSDK Log:
https://developer.huawei.com/repo/com/huawei/hms/log/5.0.0.301/log-5.0.0.301.aar
HMSSDK Network-Common:
https://developer.huawei.com/repo/com/huawei/hms/network-common/4.0.2.300/network-common-4.0.2.300.aar
HMSSDK Network-Grs:
https://developer.huawei.com/repo/com/huawei/hms/network-grs/4.0.2.300/network-grs-4.0.2.300.aar
HMSSDK Stats:
https://developer.huawei.com/repo/com/huawei/hms/stats/5.0.0.301/stats-5.0.0.301.aar
HMSSDK UI:
https://developer.huawei.com/repo/com/huawei/hms/ui/5.0.0.301/ui-5.0.0.301.aar
HMSSDK Update:
https://developer.huawei.com/repo/com/huawei/hms/update/2.0.6.302/update-2.0.6.302.aar
HMSSDK IAP:
https://developer.huawei.com/repo/com/huawei/hms/iap/5.0.2.300/iap-5.0.2.300.aar
2. Open AAR packages with rar tool and rename the class.jar and AndroidManifest.xml files. And save those jar file inside libs folder (It is recommended that the two files be renamed consistently with the AAR package names.).
3. Copy required permissions in the <manifest> section in B4A IDE.
4. Copy all the configurations in <application> section.
5. Change ${applicationId} to $PACKAGE$.
6. Download the configuration file(agconnect-services.json) from App Gallery Connect and add the JSON File to the assets Folder of the AAR file as shown below.
B4A will automatically incorporate files in the assets folder of an AAR package to the assets folder of your main project.
Setting Package Signing Options
To create a signed application package perform the following steps:
1. Choose Project > Build Configurations and change the B4A project Package name to the project package name configured in App Gallery Connect.
2. Choose Tools > Private Sign Key and select the SHA256 signature file specified in AppGallery Connect as the B4A project signature file.
2. Declare MainApplication in the Manifest file.
The path of MainApplication must also be the path to src folder where MainApplication is located.
Encapsulating Java Files Using SLC
1. Create Library as parent and then create bin, libs and src as subfolder in the project directory
2. Develop java project inside the following path:
Choose Library Folder > src > b4x > iap > demo
3. Import the following two lines of code to each Java file.
Code:
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.*;
import com.huawei.hmf.tasks.Task;
import android.content.Intent;
import anywheresoftware.b4a.IOnActivityResult;
4. Add necessary annotations to the Java files.
Code:
@DependsOn(values={ "agconnect-core-1.4.0.300.aar",
"base-5.0.0.301.aar",
"network-common-4.0.2.300.aar",
"network-grs-4.0.2.300.aar",
"iap-5.0.2.300.aar",
"availableupdate-5.0.0.301.aar",
"device-5.0.0.301.aar",
"log-5.0.0.301.aar",
"stats-5.0.0.301.aar",
"tasks-1.4.1.300.aar",
"ui-5.0.0.301.aar",
"update-2.0.6.302.aar",
})
5. Modify the context.
B4A does not recognize the Context class. Therefore, when parsing a class that contains @version (1.0f) annotation, it will report an error if a method of the class has referenced Context . In this case, you need to change Context to B4A object BA.
Code:
@ShortName("IAPWork")
public class IAPWork {
public static String eventName = "listener";
public static String TAG = "IAP_Kit";
public static BA ba;
public void init(Context context) {
AGConnectServicesConfig.fromContext(context).overlayWith(new LazyInputStream(context) {
@Override
public InputStream get(Context context) {
try {
return context.getAssets().open("agconnect-services.json");
} catch (IOException e) {
e.printStackTrace();
BA.Log(e.toString());
}
return null;
}
});
}
public void loadProduct(BA ba1) {
ba = ba1;
// obtain in-app product details configured in AppGallery Connect, and then show the products
IapClient iapClient = Iap.getIapClient(ba.context);
Task<ProductInfoResult> task = iapClient.obtainProductInfo(createProductInfoReq());
task.addOnSuccessListener(new OnSuccessListener<ProductInfoResult>() {
@Override
public void onSuccess(ProductInfoResult result) {
ba.raiseEventFromUI(this, eventName + "_iaparray", result.toString());
if (result != null && !result.getProductInfoList().isEmpty()) {
List<ProductInfo> productInfoList = result.getProductInfoList();
for (ProductInfo productInfo : productInfoList) {
ba.raiseEventFromUI(this, eventName + "_iaptext", productInfo.getProductName(), productInfo.getProductId(), productInfo.getPrice());
}
//ba.raiseEventFromUI(this,eventName+ "_iaparray",new Object[] {productInfoList} );
// showProduct(result.getProductInfoList());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, e.getMessage());
if (e instanceof IapApiException) {
IapApiException iapApiException = (IapApiException) e;
int returnCode = iapApiException.getStatusCode();
if (returnCode == OrderStatusCode.ORDER_HWID_NOT_LOGIN) {
ba.raiseEventFromUI(this, eventName + "_iaparray", "Please sign in to the app with a HUAWEI ID.");
} else {
ba.raiseEventFromUI(this, eventName + "_iaparray", e.getMessage());
// Toast.makeText(ba.context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
ba.raiseEventFromUI(this, eventName + "_iaparray", "error");
// Toast.makeText(ba.context, "error", Toast.LENGTH_SHORT).show();
}
}
});
}
private ProductInfoReq createProductInfoReq() {
ProductInfoReq req = new ProductInfoReq();
// In-app product type contains:
// 0: consumable
// 1: non-consumable
// 2: auto-renewable subscription
req.setPriceType(IapClient.PriceType.IN_APP_CONSUMABLE);
ArrayList<String> productIds = new ArrayList<>();
// Pass in the item_productId list of products to be queried.
// The product ID is the same as that set by a developer when configuring product information in AppGallery Connect.
productIds.add("ProductID1");
productIds.add("ProductID2");
productIds.add("ProductID3");
productIds.add("ProductID4");
req.setProductIds(productIds);
ba.raiseEventFromUI(this, eventName + "_iaparray", productIds.get(0));
return req;
}
}
Tips & Tricks
The account for sandbox testing takes effect 30 minutes to 1 hour after being added. Check whether the current account can be used in the sandbox testing.
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
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