Introduction
Machine learning is an application of artificial intelligence that provides systems the ability to automatically learn and improve from experience without being explicitly programmed. Machine learning focuses on the development of computer programs that can access data and use it learn.
HMS ML Kit allow to support diverse artificial intelligence applications throughout a wide range of industries.
HMS ML Kit Services
1. Text-related Services
2. Language/Voice-related Services
3. Image-related Services
4. Face/Body-related Services
5. Custom Model
In this article we will focus on text related services provided by HMS ML 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 should 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.
Text-related Services
There are four type of services which comes under text related service:
1. Text Recognition
2. Document Recognition
3. Bank Card Recognition
4. General Card Recognition
Here we will use three services that is Text Recognition, Bank Card Recognition and General Card Recognition to showcase the power HMS ML Kit in Ionic application.
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 Ml Kit Plugin. Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install <CORDOVA_MLKIT_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 (ex: 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:
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
14) Add plugin to the build.gradle file in the app directory as show below:
15) Add ads service implementation into to dependencies section of build.gradle file in the app directory as show below:
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
Install FileChooser
We need to install FileChooser to select a file or in this case an image, returns a file URI. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-filechooser
npm install [user=1329689]@iONiC[/user]-native/file-chooser
ionic cap sync
Android Permission
We need android permission in order to allow our user to give their permission to the application like camera permission, storage permission etc. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-android-permissions
npm install [user=1329689]@iONiC[/user]-native/android-permissions
ionic cap sync
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 { AndroidPermissions } from [user=1329689]@iONiC[/user]-native/android-permissions/ngx';
import { FileChooser } from [user=1329689]@iONiC[/user]-native/file-chooser/ngx';
import { HMSMLKit } from [user=1329689]@iONiC[/user]-native/hms-ml/ngx'
import { FilePath } from [user=1329689]@iONiC[/user]-native/file-path/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
AndroidPermissions,
FileChooser,
HMSMLKit,
FilePath,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
For more information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202369186369300340&fid=0101187876626530001
Related
More articles like this, you can visit HUAWEI Developer Forum.
This post will show you how to use Cocos2d-x on Android and integrate with Huawei mobile services.
What is Cocos?
Cocos have two main product Cocos Creator and Cocos2d-x.
Cocos2d-x — is a open-source, cross platform game engine. It includes the engine and the cocos command-line tool. Its let us to develop in C++, JavaScript or Lua.
{
"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"
}
Cocos Creator — is a unified game development tool focused on content creation. You can
create your entire game, from start to finish, using this tool. It uses JavaScript natively and can
export to C++. Read more about Cocos Creator. Cocos Creator integrates the entire mobile browser
game solution into the editor tool, eliminating the need to shuttle between multiple
software applications.
With the Cocos Creator editor open, a one-click automated process takes the least amount of time.
In this article we will focus Cocos2d-x game engine integration.
You can download stabile version from here. (cocos2d-x-3.17.2 used for this article).
Build Requirements
Python 2.7.5+(NOT Python 3)
NDK r16+ is required to build Android games(with android studio we will add)
Android Studio 3.0.0+ to build Android games(tested with 3.6.3)
Windows 7+ (tested with Windows 10)
Environment Setup
Unzip cocos installed file then run this command for setup environment.
Code:
cd cocos2d-x
setup.py
NDK Root Path Configuration
Skip this steps when the command prompt ask you to enter android sdk root path and ndk root path. We will configure paths with android studio. After installation restart your computer.
How to create a new game?
Single command line is enough to create a game.
Code:
cocos new <game name> -p
<package identifier> -l <language> -d <location>
cocos new MyGame -p
com.package.name -l cpp -d N PROJECTS_DIR
You can also create a Lua project with -l lua or JS project with -l js .
After create new project. Open “proj.android” folder in anroid studio.
Android Studio Configurations
File -> Settings -> Android SDK -> SDK Platforms: Download your android version to use
File -> Settings -> Android SDK -> SDK Tools:
Install
Android SDK Build-Tools
NDK
CMake
Android Emulator
Android SDK Platform-Tools
Android SDK Tools
Google USB Driver
Inter x86 Emulator
Note: Configure CPU architecture with “grandle.properties” file;
update Line "34" PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86
Update android gradle plugin lates version. “../proj.android/gradle/wrapper/gradle-wrapper.properties”
NDK configuration
File -> Project Structure -> SDK Location -> Android SDK Location: Choose default one (we already download).
Cocos2d-x Main Components
Director: You can think of the Director the same way you think about a movie director.
The Director controls every aspect of your game. What is shown on the screen, what sounds
are played, what happens with player input, and much more.
Scene: A Scene is a container that holds Sprites, Labels, Nodes and other objects that
your game needs. A Scene is responsible for running game logic and rendering the content on a
per-frame basis.
Sprite: A Sprite is a 2D image that can be animated or transformed by changing its properties.
Most all games will havemultiple Sprite objects ranging from the hero, an enemy or a level boss.
Scene Graph: The scene graph is a data structure that arranges a graphical scene, into a
tree structure. This tree structure is what is used to render objects onscreen in a specific order.
Renderer: In an oversimplified definition the renderer is responsible for taking everything
you want on the screen and getting it there, technically. No need to delve into this further at this time.
Events: What do you do when the player moves around? What about touch events
or keyboard input? These all trigger events that can be acted upon as needed.
Audio: Perhaps your game has background music and or sound effects.
UI Components: Things like Button, Label, ScrollView, etc. Items that help you layout your
game and related interfaces.
Physics Engine: The physics engine is responsible for emulating the laws of physics
realistically within the application.
Well a Sprite is only a Sprite if you move it around. If you don’t move it around it is just a Node
How to use Huawei Mobile Services ?
Cocos2d-x provide the sdkbox to integrate mobile services. This tool help us to use Huawei mobile services.
This tools now supporting Account kit, Game Service, In-App Purchases. Ads kit now developing process and push kit also will come next versions.
Dowload from this link. Drag and drop zip file to your project.
Open a terminal and use the following command to install the SDKBOX HMS plugin. Normally we can download hms plugin directly but now its stating process because of that I use staging server to get plugin.
Code:
sdkbox import hms//staging server
sdkbox import HMS --staging
After this command our project build.gradle files will updated for HMS. If dependencies version are old you can update them.
HMS for android
Create App in AppGallery
Enable Module you need(enable AccountKit and Game Service,we will use this)
Configure app signature(release)
download app info agconnect-services.json
For detail you can follow this link.
Update gradle.properties file:
PROP_MIN_SDK_VERSION=17
RELEASE_STORE_FILE=yourSignFile.jks
RELEASE_STORE_PASSWORD=password
RELEASE_KEY_ALIAS=alias
RELEASE_KEY_PASSWORD=password
Cocos Development
Now our application is ready to run with HMS. We will invoke HMS function via plugin, before that I want to show Cocos file structure.
The resources folder is a common repository for all the various assets that your game will use, such as graphics, sound, etc.
The Classes folder is perhaps most important of all, this is where your non platform specific code goes.
An AppDelegate is a helper object that goes with the main window and handles events common to applications such as starting up, minimizing and closing. You won’t really spend much time here, that instead is where the Scene file comes in.
AppDelegate header is pretty straight forward, it declares a constructor, destructor and four methods, initGLContextAttrs, applicationDidFinishLaunching, applicationDidEnterBackground and applicationWillEnterForeground. All four of these methods are pure virtual functions from ApplicationProtocol, from which Application ( and in turn AppDelegate ) inherit, so we must provide an implementation of each, even if it’s empty
Initialize HMS
We will use AppDelegate.cpp for initialize the plugin.
Code:
#include
"PluginHMS/PluginHMS.h"
bool AppDelegate::applicationDidFinishLaunching()
{
#ifdef SDKBOX_ENABLED
sdkbox::PluginHMS::init();
#endif
AppDelegate class create HelloWorld screen. We will create menu screen for login and logout with HMS account kit.
Update HelloWorld.h for menu.
Code:
public:
......
void showMenu(const std::string& menuName);
void genMainMenu();
void genAccountMenu();
private:
cocos2d::Label*mTitle;
cocos2d::Menu*mMenu;
We will create listener for HMS and we will invoke this in init() function.
Code:
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "PluginHMS/PluginHMS.h"
#include "json/rapidjson.h"
#include "json/document.h"
.....
//Listener for HMS
class PluginHMSListener : public sdkbox::HMSListener {
public:
PluginHMSListener(HelloWorld* scene): hw(scene) {
}
void onLogin(int code, const std::string& errorOrJson) {
cocos2d::log("HMS onLogin: %d, %s", code, errorOrJson.c_str());
if (0 != code) {
showMsg("login failed:" + errorOrJson);
return;
}
rapidjson::Document doc;
doc.Parse(errorOrJson.c_str());
std::ostringstream ss;
ss << "Login success:" << doc["displayName"].GetString();
showMsg(ss.str());
}
private:
HelloWorld* hw;
};
bool HelloWorld::init()
{
sdkbox::PluginHMS::setListener(new PluginHMSListener(this));
sdkbox::PluginHMS::buoyShow();
......
return true;
}
This function for login via HMS.
Code:
void HelloWorld::genAccountMenu() {
mMenu->addChild(MenuItemLabel::create(Label::createWithSystemFont("Login", "arial", 24), [](Ref*){
showMsg("to login...");
// sdkbox::PluginHMS::login(0); // slient login
sdkbox::PluginHMS::login(1); // login (id token)
// sdkbox::PluginHMS::login(2); // login (author code)
}));
mMenu->addChild(MenuItemLabel::create(Label::createWithSystemFont("Logout", "arial", 24), [](Ref*){
showMsg("to logout...");
sdkbox::PluginHMS::logout();
}));
}
Running a project
First runnig may take a long time. It will compile more than 600 cpp file.
After clicking “Account Test”:
After clicking “Login”.
Finally our project connected Huawei account.
Thanks for reading.
I hope this gives you a starting point for Cocos2d-x and integration with HMS. Feel free to check out the full source code in github.
Links:
codelab
Codelabs provide a technical expert guidance, tutorial and hands-on coding experience. Here you can learn about…
developer.huawei.com
http://docs.sdkbox.com/en/plugins/hms/v3-cpp/
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202333954713070046&fid=0101187876626530001
A Splash Ad is called Splash Ad because it is a full page interstitial ad that is displayed immediately after the application is launched.
A Splash Ad first displays a full-page splash screen that you define (for example your app's logo or branding) followed by a full page ad.
Huawei Ads kit offers Splash Ad to use in your business to achieve certain business and advertisement goals by following the digital marketing practices.
Huawei Ads Kit demonstrate an easy and efficient way to implement the splash ads within your application.
Prerequisite
1. Must have a Huawei Developer Account
2. Must have a Huawei phone with HMS 4.0.0.300 or later
3. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
1. React Native CLI : 2.0.1
2. Gradle Version: 6.0.1
3. Gradle Plugin Version: 3.5.2
4. React Native Site Kit SDK : 4.0.4
5. React-native-hms-site gradle dependency
6. AGCP gradle dependency
Development Overview
Preparation
1. Create an app or project in the Huawei app gallery connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project, use the below command
“react-native init project name”
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
Tips
1. agconnect-services.json is not required for integrating the hms-ads-sdk.
2. Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Ads Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-ads
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
· Creating a Splash Ad
· Setting Ad Slot ID
· Customizing Splash Screen
· Setting Ad Request Parameters
· Display Ad
· Listen to Ad Events
· Testing
HMS Splash Ads aligned with the application and device layout seamlessly, however these can be customised as well.
Creating a Splash Ad
HMSSplash component needs to be added to import the Splash ads in the code.
Code:
import {HMSSplash} from 'react-native-hms-ads';
Setting Ad Slot ID
setAdId() is the method used for creating an ad slot ID reference to the app.js file.
Code:
HMSSplash.setAdId("AdSlotId");
Where AdSlotId = "testd7c5cewoj6" and can also be defined as Video or Image media types
Note
Developers can use publisher services to create the Ad Slot ID. Refer this article to know the process for creating the slot Id’s
Customizing Splash Screen
Splash ads can also be customized as explained below.
Create a function in app.js file and add different customizations.
Changing the logo text or setting up the copy write text to your advertisement.
Code:
HMSSplash.setLogoText('HMS App');
HMSSplash.setCopyrightText('Copyright HMS');
Setting Ad Request Parameters
setAdParam() is used to set the set the additional parameters to get specific ads for specific audience. Below code can be executed on the button click to ad additional parameters.
Code:
import {ContentClassification,UnderAge } from 'react-native-hms-ads';
HMSSplash.setAdParam({
adContentClassification:
ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
// appCountry: '',
// appLang: '',
// belongCountryCode: '',
gender: Gender.UNKNOWN,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
// requestOrigin: '',
tagForChildProtection:
TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
// targetingContentUrl: '',
}
Display Ad
Show() method is used to display the ads on the button click.
Code:
<Button title="Splash" color="green" onPress={() => HMSSplash.show()}/>
Listen to Ad Events
Listener functions can be triggered with the different ad actions and associated events.
Code:
HMSSplash.adLoadedListenerAdd(() => {
toast('HMSSplash adLoaded');
});
// HMSSplash.adLoadedListenerRemove();
HMSSplash.adFailedToLoadListenerAdd(() => {
toast('HMSSplash adFailedToLoad');
});
// HMSSplash.adFailedToLoadListenerRemove();
HMSSplash.adDismissedListenerAdd(() => {
toast('HMSSplash adDismissed');
});
// HMSSplash.adDismissedListenerRemove();
HMSSplash.adShowedListenerAdd(() => {
toast('HMSSplash adShowed');
});
// HMSSplash.adShowedListenerRemove();
HMSSplash.adClickListenerAdd(() => {
toast('HMSSplash adClick');
});
Testing
Run the below command to build the project
Code:
React-native run-android
Upon successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
{
"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"
}
References
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050196714
Conclusion
Adding Splash Ads seems very easy.
Introduction
Back in the 90’s, it was a revolutionary to have your own website and putting an advertisement in the website was the only source of revenue. But today as space matures, it’s essential for brands to have a clear strategy to monetize their mobile presence. Some companies charge their users before downloading their apps. Others depend on in-app advertising as their sole revenue stream. But, for a lot of brands, their mobile monetization strategy relies entirely (or some part) on In App Purchase. To summarise, when a customer spends money within a mobile app, that’s an in-app purchase.
To make easier for users to make payments and developers to focus solely on app innovation, Huawei provided us with an extraordinary kit i.e. HMS Core In App Purchase (IAP) Kit. HMS In App Purchase helps developers in variety of situation to earn revenue such as paying for access to a dating app’s special features, subscribing to a streaming music app’s premium tier, buying more gold bars in games etc.
In this article, we are going to integrate HMS Core In App Purchase Kit into an Ionic application.
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"
}
The above Ionic framework demo application is created with the same concept of my previous work and that is a quiz game which was created using android native and java as language. The concept of this game is to show In App Purchase in a game and how user can purchase subscription and non-subscription products. The name of the game is Quiz Mania. Below is the demo of that application.
To know more click on the link below:
https://forums.developer.huawei.com/forumPortal/en/topic/0201255229704010231
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 @ionic/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 In App Purchase 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) Run the following command in the root directory of your Ionic project to install HMS IAP kit it through npm.
Code:
npm install @hmscore/cordova-plugin-hms-iap
8) If you want full Ionic support with code completion etc., install @iONiC-native/core in your project.
Code:
npm install @ionic-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-iap/ionic/dist/hms-in-app-purchases node_modules/@ionic-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 (ex: 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
}
}
}
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 site kit service implementation into to dependencies section of build.gradle file in the app directory as show below:
Code:
dependencies {
….
implementation 'com.huawei.hms:iap:5.0.4.301'
}
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
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0204418699662160038
{
"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"
}
Introduction
In this article, I will explain how to subscribe the topic using integrating the Huawei Push Kit into React Native project. React Native is a tool announced and open-sourced by Facebook in April 2015. It is a cross-platform mobile app development framework that is derived from Facebook's earlier open-source JavaScript framework React. It helps to adapt to native mobile app platforms.
Push Kit
Push notifications offers a great way to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application. Push Kit supports two types of messages: notification messages and data messages. You can send notifications and data messages to your users from your server using the Push Kit APIs or directly from the AppGallery Push Kit Console.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.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. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies and React Native Project Preparation
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Push Kit.
9. Environment set up, refer below link
https://reactnative.dev/docs/environment-setup
10. Create project using below command
Code:
react-native init projectname
11. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
12. Integrate the Hmspush plugin
npm i @hmscore/react-native-hms-push
13. Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
14. Add to dependencies.
Code:
Implementation project (': react-native-hms-push)
15. Project level build.gradle/buildScript directory set minSdkVersion to 19 or higher higher. In android/signingConfigs/config node, enter the keystore file credentials.
Code:
signingConfigs {
config {
storeFile file(<keystore_file_name>)
storePassword ‘<store_password>’
keyAlias ‘<alias>’
keyPassword ‘<key_password>’
}
}
16. Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
-Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
-Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
17. Navigate to android/settings.gradle and add the following.
Code:
include ':react-native-hms-push'
project(':react-native-hms-push').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-push/android')
18. Add below permissions in Android.manifest file.
XML:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development
Obtain a Token:
In order to push notifications to a device, you need to obtain a token. To get the token, use getToken method from HmsPushInstanceId module.
JavaScript:
HmsPushInstanceId.getToken("")
.then((result) => {
this.log("getToken", result);
})
.catch((err) => {
alert("[getToken] Error/Exception: " + JSON.stringify(err));
});
Add Push Notifications
To push a notification message to your device, navigate to your Huawei developer console and choose Project>Growing>Push Kit>Add notification.
Subscribing the Topics
Subscribing to a topic enables the users to receive data messages by the subscribed topic. To subscribe a topic, use subscribe method from HmsPushMessaging module.
JavaScript:
subscribe() {
HmsPushMessaging.subscribe(this.state.topic)
.then((result) => {
this.log("subscribe", result);
})
.catch((err) => {
alert("[subscribe] Error/Exception: " + JSON.stringify(err));
});
}
To push a notification or data message by topic, navigate to the Huawei push console to push a new notification, choose push scope as Subscriber and then select the topic of the message to be sent.
Unsubscribe the topics
Unsubscribing from a topic lets the user not to listen data messages by the unsubscribed topic. To unsubscribe from a topic, use unsubscribe method of the HmsPushMessaging module.
JavaScript:
unsubscribe() {
HmsPushMessaging.unsubscribe(this.state.topic)
.then((result) => {
this.log("unsubscribe", result);
})
.catch((err) => {
alert("[unsubscribe] Error/Exception: " + JSON.stringify(err));
});
}
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
5. For project cleaning navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion
In this article, we can learn about how to integrate Push Kit and how to subscribe the topic in React native project. It will guide you to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application.
Reference
Push Kit: Documentation
Push Kit: Training Video
{
"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"
}
Introduction
In this article, I will be integrating Huawei Scan Kit in an Application. Huawei Scan Kit scans and parses all major 1D and 2D Barcodes as well as generates barcode which helps you to quickly build barcode scanning functions into your apps. Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and can scan a very small barcode in the same way. It works even in suboptimal situations, such as under dim lighting or when the barcode is reflective, dirty, blurry, or printed on a cylindrical surface. This leads to a higher scanning success rate, and an improved user experience.
React Native
React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.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. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save.
React Native Project Preparation
8. Environment set up, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
9. Create project using below command.
Code:
react-native init project name
10. Download Plugin Using NPM.
To integrate the plugin, ensure that the preparation step is completed and download the plugin using the following command.
Code:
npm i @hmscore/react-native-hms-scan
11. Open settings.gradle located under the project-dir > android directory and add
Code:
include ':react-native-hms-scan'
project(':react-native-hms-scan').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-scan/android')
12. Open build.gradle file which is located under project.dir > android > app directory.
Code:
Configure build dependencies.
dependencies {
...
implementation project(":react-native-hms-scan")
...
}
13. Add following in the MainApplication file
Code:
import com.huawei.hms.rn.scan.RNHMSScanPackage;
List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new RNHMSScanPackage());
return packages;
14. Add below permissions to Android.manifest file.
Code:
<p><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
p>
Development
Request the permissions in the code dynamically.
Code:
import ScanPlugin from '@hmscore/react-native-hms-scan';
//Call requestCameraAndStoragePermission API.
ScanPlugin.Permission.requestCameraAndStoragePermission()
.then((res) => console.log("Result:", res));
Check whether the required permissions are enabled before scanning a barcode.
Code:
//Call hasCameraAndStoragePermission API.
ScanPlugin.Permission.hasCameraAndStoragePermission()
.then((res) => console.log("Result:", res));
Generate Barcode
Code:
ScanPlugin.Utils.buildBitmap({
content: this.state.content,
type: this.state.type,
width: this.state.width,
height: this.state.height,
margin: this.state.margin,
color: this.state.color,
backgroundColor: this.state.backgroundColor,
})
.then((res) => {
this.setState({showImage: true});
this.setState({base64ImageData: res});
})
Decode Bitmap
Code:
ScanPlugin.Utils.decodeWithBitmap({
data: barcode_images.barcode,
scanType: ScanPlugin.ScanType,
additionalScanTypes: [],
})
.then((res) =>
this.setState({
decodesBitmap: [...this.state.decodesBitmap, res],
}),
) this.setState({base64ImageData: res});
The process of using Scan Kit in Default View mode as follows:
Check whether the app has the camera access and file read permissions.
If the app has the required permissions, call the startDefaultView API from Utils module of the Scan Kit React Native Plugin to bring up the scanning UI.
Check whether the scanning UI is successfully displayed.
Obtain the scanning result based on the scanning status.
Construct a DefaultViewRequest object.
The parameters are as follows:
Code:
]import ScanPlugin from '@hmscore/react-native-hms-scan';
let defaultViewRequest = {
scanType: ScanPlugin.ScanType.All,
additionalScanTypes: [],
}
Call the startDefaultView API with the request object to bring up the scanning UI and obtain the scanning result of Default View which is a ScanResponse object.
Code:
ScanPlugin.Utils.startDefaultView(defaultViewRequest)
.then((res) => console.log(res))
.catch((e) => console.log(e))
Construct a CustomizedViewRequest object in order to customize the scanning UI.
Code:
ScanPlugin.CustomizedView.startCustomizedView({
scanType: ScanPlugin.ScanType,
additionalScanTypes: [],
rectHeight: 200,
rectWidth: 200,
continuouslyScan: true,
isFlashAvailable: false,
flashOnLightChange: false,
isGalleryAvailable: false,
})
.then((res) =>
this.setState({
decodesCustom: [...this.state.decodesCustom, res],
}),
)
Testing
Run the android App using the below command.
Code:
react-native run-android
Result
Tips and Tricks
1. Check supported 13 barcode formats here.
2. Only add configurations for Scan Kit to support required formats of barcode as this will improve the scanning speed.
3. HMS react native plugin does not support Expo CLI and only support React Native CLI
Conclusion
In this article, we have learnt that how to integrate scan kit into the app, quickly build barcode scanning functions into your apps. Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and can scan a very small barcode in the same way.
Reference
Scan Kit: Documentation
Scan Kit: Training Video