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/
Related
More articles like this, you can visit HUAWEI Developer Forum
HUAWEI Analytics Kit 5.0 version has been updated, and it supports iOS SDK now, enabling one-stop, unified analysis of cross-platform Android and iOS users. It looks into user-centric analysis and helps you understand user behavior on the Android and iOS platforms. Today I want to share with you how to add Analytics Kit to your iOS App. The version I integrated is 5.0.0.300.
The general steps we will walk through include:
Configuring App Information in AppGallery Connect
Integrating the HMS Core SDK
Accessing HUAWEI Analytics Kit
Configuring App Information in AppGallery Connect
Follow the steps below to configure App Information in AppGallery Connect for your iOS application. If you have both an Android and an iOS version of your app, you can set them within the same project, this will allow you to finish the data analysis conveniently.
{
"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"
}
Getting Started:
1. Have your Bundle ID ready for your iOS app (ask your developers for this).
2. Go to AppGallery Connect and create a new project.
Once you’ve created a new project, you’ll see a page, and the side navigation bar shows the AGC's various function menus.
3. Click Add app, and create an iOS application.
Here the App package ID is the Bundle ID.
Click OK, and then you will get the configuration file agconnect-services.plist.
Click Manage APIs, and here we’ve already had the Analytics API enabled.
Back to the side navigation bar, and go to the HUAWEI Analytics tab, you will see all kinds of functions, including User analysis, Behavior analysis, etc. Select any menu to Enable Analytics service.
On the Project access settings page, set the data storage location, time zone, currency, user data storage time, and calendar week, and click Finish.
Integrating the HMS Core SDK (in Cocoapods Mode)
I prefer the Cocoapods Mode. You can also integrate the HMS Core SDK into the Xcode Project Manually.
1. Add the AppGallery Connect configuration file of the app to your XCode project.
a. Click Download agconnect-services.plist to obtain your iOS config file (agconnect-services.plist).
b. Move your agconnect-services.plist file into the root of your Xcode project.
2. Edit the Podfile file
a. Create a Podfile if you don't already have one:
$ cd your-project-directory
$ pod init
b. To your Podfile, add the pods that you want to use in your app: Add pod 'HiAnalytics', that is, the dependency for pod.
Example Podfile file:
Code:
# Uncomment the next line to define a global platform for your project
# platform :iOS, '9.0'
target 'HiAnalyticsSwiftDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for HiAnalyticsSwiftDemo
pod 'HiAnalytics'
target 'HiAnalyticsSwiftDemoUITests' do
# Pods for testing
end
end
c. Install the pods, then open your .xcworkspace file to see the project in Xcode:
$ pod install
$ open your-project.xcworkspace
Accessing HUAWEI Analytics Kit
1. Initialize Analytics SDK in your app
The final step is to add initialization code to your application. Initialize AppDelegate through the config interface.
Objective C sample code: Perform initialization in AppDelegate.m.
Code:
#import "AppDelegate.h"
#import <HiAnalytics/HiAnalytics.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
...
- (BOOL)Application:(UIApplication *)Application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after Application launch.
[HiAnalytics config];//Initialization
return YES;
}
...
@end
Swift code example: Perform initialization in AppDelegate.swift.
Code:
import UIKit
import HiAnalytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func Application(_ Application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after Application launch.
HiAnalytics.config();//Initialization
return true
}
...
}
2. Record defined events using the onEvent API.
For definitions of the events, please refer to Event Description.
3. Call APIs of HUAWEI Analytics Kit to implement the corresponding functions. For details, please refer to API Reference.
During the development, you can use DebugView to view the event records in real time, observe the results, and adjust the event tracing scheme.
Enabling/Disabling the Debug Mode
1.To enable the debug mode:
Go to Product > Scheme > Edit Scheme from the Xcode menu. On the Arguments page, click + to add the -HADebugEnabled parameter. After the parameter is added, click Close to save the setting.
Code:
1. –HADebugEnabled
2.To disable the debug mode
Code:
1. -HADebugDisabled
After the data is successfully reported, you can go to HUAWEI App Debugging to view the data, as shown in the following figure.
Q&A:
1. I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Face problems during development? Take it easy. Go to Stack Overflow and raise your questions. Huawei experts will get back to you as soon as possible.
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest
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
Introduction
{
"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"
}
Growing old I always wondered how a product will have a barcode format on its back, how this has been generated and why this is required?
I found my answers when I searched this on internet during my college days and could not find any potential way to have this integrated on a small hand held device, however that era had lot many bulky barcode scanners available in the market and guess what!! They were huge at price and away from the reach of common people.
So the science and Technology filled this gap by providing us easy to use readymade API’s to integrate the scanning capabilities into our mobile applications.
But this was not sufficient as the developer always look for hassle free API integration with high quality results.
I was dumbfounded by the capabilities offered by the Huawei Scan kit as I started working on the QR code scanner application.
Huawei Scan Kit provides robust API’s to developer and deliver smooth and high quality barcode or QR code scanner applications.
Huawei Scan kit can also detect and magnify the slightly blurred barcodes places at a distance under the dim light.
Huawei Scan Kit offers, as follows:
Scanning of all the major barcodes by automatically detecting, magnifying and recognizing them
Parsing of all major 1D and 2D barcodes
Barcode generation.
Development Overview
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: 4.0.1
4. React Native Scan Kit SDK : 1.2.2.300
5. react-native-hms-scan kit gradle dependency
6. AGCP gradle dependency
Software Requirements
1. Java SDK 1.8 or later
2. Android 5.0 or later
Preparation
1. Create a react native project using React Native CLI and open android directory.
2. Download the React Native Scan Kit SDK and paste It under Node modules directory of React Native project.
3. Create an app and project in the Huawei AppGallery Connect.
4. Provide the SHA Key and App Package name of the project.
5. Download the agconnect-services.json file and paste to the app folder of your android folder.
Integration
Add below to build.gradle (project)file, under buildscript/repositories and allprojects/repositories.
Code:
Maven {url 'http://developer.huawei.com/repo/'}
Add below to build.gradle (app) file, under dependencies to use the Scan kit SDK in your React Native application.
Code:
dependencies{
// Import the SDK.
implementation project(":react-native-hms-scan")
}
Add below under Settings.Gradle file.
Code:
include ':react-native-hms-scan'
Code:
project(':react-native-hms-scan').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-scan/android')
Add below under MainApplication.java file.
Code:
import com.huawei.hms.rn.scan.RNHMSScanPackage;
interface// parclable @Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
//Add following line. Don't forget to add import statement also.
packages.add(new RNHMSScanPackage());
return packages;
}
...
};
Use case
Huawei scan kit provides 5 different API’s to support different requirements and use case ranging from text reading application to payment applications. Below are the supported functionalities for same.
In this article the highlight would be generation of QR code for a URL access and also we will see how can we fetch the QR code information from the QR codes using Default View HMS react native API’s.
Adding Required Permission
React Native plugin for scan kit requires Camera and Storage permissions, same needs to be added into the APP.js file on a button click.
Code:
import ScanPlugin from "@hmscore/react-native-hms-scan";
<Button
color="Grey "
title="Request Permission"
onPress={() =>
ScanPlugin.Permission.requestCameraAndStoragePermission().then(
(res) => {
console.log("result", res);
this.setState({permissionGranted: res});
},
)
}
/>
//Also check if the permission is enabled or not prior further operation
const response = await ScanPlugin.Permission.hasCameraAndStoragePermission();
this.setState({permissionGranted: response});
Generating Barcodes
Use the barcode generation API of Scan Kit to generate a barcode as follows:
The app specifies the barcode width and height, character string and format.
The app calls the barcode generation API, buildBitmap from Utils module of the Scan Kit React Native Plugin.
The HMS Scan React Native Plugin sends the generated barcode to the app as Base64 encoded String of Bitmap Image.
Parameters
Set the character string that will be converted into a barcode, set its width and height, and specify the barcode format.
The parameters are as follows:
content: (Required) Barcode content.
width: (Optional) Width of a barcode to be generated.
height: (Optional) Height of a barcode to be generated.
type: (Optional) Barcode format.
margin: (Optional) Barcode margin.
bitmapColor: (Optional) Barcode colour.
backgroundColor: (Optional) Barcode background colour.
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0203418564668030036
Informative
INTRODUCTION
In this article we will learn how to integrate the Push Kit into a Unity project from start to finish, constantly in groups and video game development communities questions and difficulties are triggered for developers so within this article I would like to touch on different problems that can be easily solved just by following a few steps and modifying certain values within the Unity editor.
{
"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"
}
MOST COMMON QUESTIONS IN DEV COMMUNITIES
Through the development communities, we have been presented with different questions that I have been collecting little by little, below I share some that are commonly repeated.
After importing the Evil Mind plugin, my project won't run on my device?
Add the Push Manager prefab and when I run the game in game mode it doesn't compile
How can I get the token that Push Kit returns to me when it is executed?
Unity cannot locate the Android SDK and I cannot run the project.
ARTICLE GOAL
Our goal in this article will be to be able to send a notification to our phone from App Gallery Connect using the token that HMS Push Kit gives us, we will achieve this by solving the problems that arise at the time of configuration.
STEPS
Configuration App Gallery Connect.
Configure Unity to run our project.
Import Evil Mind Plugin.
Configure our project with App Gallery Connect.
Create the class and the code to get the answer.
Obtain the log of our device
Add the token to App Gallery Connect
Try our game
APP GALLERY CONFIGURATION
As we know we must create a project in App Gallery Connect and add an app in order to configure the necessary data for our project. Let's start by logging into the AGC console to create a project.
Within the projects section we can create a new project where we must create an App which will be added to our project.
Once the application is created we must fill in the following data in the form, for this it will be necessary to create our project in Unity and assign the package name.
Let's go to unity to create the necessary data, Open unity and create a new project. Once the project is created, select Build Settings> Player Settings to assign your game data.
Remember to confirm that in Other Settings you also have your package correctly. Here we will answer one of the questions we have at the beginning of this article.
After importing the Evil Mind plugin, my project won't run on my device? This generally happens to us because we do not have the Backend value configured correctly and the minimum supported API, in the following image I share the data that you should place.
With this configuration we will be able to run our game on the device that we have connected, remember that if you are using a GMS device it will be necessary to install the HMS Core apk which you can download from this league. https://m.apkpure.com/es/hms-core/com.huawei.hwid/download once downloaded you can run huawei mobile services.
Running your project on the device should have a screen similar to this, we have not added the button yet but we will do it later, the important thing is that your scene compiles correctly.
UNITY CONFIGURATION
Let's start now with the configuration of our project in Unity. What we must do is import the Evil Mind plugin to be able to obtain the upper menu of Huawei and to be able to place the data obtained from AGC. Download the plugin from the repository that I share with you now. https://github.com/EvilMindDevs/hms-unity-plugin
Download the pcustom package to your computer and import it into Unity.
You must import it from the import tab and select custom package, once imported an option will be enabled in the upper menu with the title of Huawei, when you click on it you will get the following pop up.
Download the json file from AGC and replace it in Unity the path to find the json you can find in the following image
Open the agconnect file and start putting the necessary data to paste into the Huawei plugin. In the image I am showing you in yellow what data you must take to place them in the plugin window.
When you finish assigning the data, click on the Configure Manifest button. IMPORTANT JUST GIVE A CLICK, OTHERWISE YOU WILL ADD LINES TO YOUR MANIFEST AND THE ERROR WILL BE PRESENTED Merge Manifest.
Check your android Manifest take into account that when you import the plugin, a default Manifest will be downloaded in your project, that Manifest Default has packages that belong to the example, so it is important that you only have the following <providers> as I show in the image
Add the Push Manager prefab to your scene, you can also add a button inside a Canvas to initialize the Push Kit service, leave it in the onStart () method;
Run your project again to identify errors if they occur during the compilation and construction of the project. This will not generate any effect in Push Kit nor will it grant you the token because we have not configured the SHA256 signature, possibly the console will indicate that the fingerprint has not been configured. We are going to configure this signature. Create your keystore in your project folder, go to the folder where your project is with your console and execute the following command.
Replace the name of your keystore
keytool -list -v -keystore d:key.keystore
Get the Sha 256 and place it in AGC.
CODING
We will create a script that is responsible for initializing the service and granting us the token of our device and then sending the notification through token.
Java:
namespace HmsPlugin
{
public class PushKitManager : MonoBehaviour, IPushListener
{
public Action<string> OnTokenSuccess { get; set; }
public Action<Exception> OnTokenFailure { get; set; }
public Action<RemoteMessage> OnMessageReceivedSuccess { get; set; }
// Start is called before the first frame update
void Start()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"[HMS] Push token from GetToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnNewToken(string token)
{
Debug.Log($"[HMS] Push token from OnNewToken is {token}");
if (token != null)
{
OnTokenSuccess?.Invoke(token);
}
}
public void OnTokenError(Exception e)
{
Debug.Log("Error asking for Push token");
Debug.Log(e.StackTrace);
OnTokenFailure?.Invoke(e);
}
public void OnMessageReceived(RemoteMessage remoteMessage)
{
OnMessageReceivedSuccess?.Invoke(remoteMessage);
}
}
}
We will also create a method only as an example to be able to initialize the service and obtain the token
Java:
public void StartNotificationService()
{
PushManager.Listener = this;
var token = PushManager.Token;
Debug.Log($"The token {token}");
if(token != null)
{
}OnTokenSuccess?.Invoke(token);
}
Now we need to obtain the token of our phone and that the Log will return us and we will place it in the push notification service.
Fill in the necessary data to send the notification such as the Title, the Body and the name of the notification. You must also configure the device parameters. In this section is where you must add the token obtained from your device.
Now just launch the notification
TIPS AND TRICKS
I dont know how to obtain logs from my Android Device. In the following steps you'll learn how to debug from your Device.
For troubleshooting and debugging, it is often very helpful to capture the device logs. The device logs contain information about the status of a running application on the device and any errors encountered. The IAP Engineering team requires logs for open issues. It is assumed here that you have an Android device configured with Developer options and attached to a PC with a USB cable. These steps show the process on a Windows system and works similarly on a Mac
1. In Unity, find the location of the Android SDK. From the Edit menu, choose Preferences/External Tools
2. Look for the Android SDK. On my system it was C:\Users\[username]\AppData\Local\Android\sdk
3. Open a command prompt, and change to this directory.
4. Change directory to the platform-tools subdirectory.
5. You should see adb.exe in this directory.
6. With the device connected via USB, run the following command:
adb devices (Mac is ./adb devices)
7. This should return device serial number followed by the word "device"
8. Run "adb logcat | findstr -i unity" (use grep on Mac) in the terminal window. This will find anything with the word "unity" in the output, case insensitive.
9. This will provide the contents of the device log that are associated with a running Unity application
The output can be quite verbose. You can browse through the log however, looking for such words as "error" and "exception". Sometimes customer support will ask for device logs, in which case you can send the output to a text file with the command "adb logcat -d | findstr -i unity > log.txt"
CONCLUSION
Push notifications are one of the trending tools in marketing arenas. No arena has been left untouched by the tool- after engaging users brilliantly on an e-commerce store, it’s the turn of the gaming app push notifications.
Mobile gaming apps have gone too far popular in today’s arena so much so that mobiles have been developed specifically for the game, consisting of the hardware that would meet the demands of the users.In this article we learned how to implement HMS Kit Push notification in oour Unity Game an it was very fast.
REFERENCES
Push Kit - Cloud Message Push- Cross-Platform Messaging Solution - HUAWEI Developer
Push Kit can satisfy the relevance and freshness of content update that your users want. Push instant messages from the cloud to user devices.
developer.huawei.com
Read In Forum
SPANISH VIDEOTUTORIAL
If you speak or understand spanish here you have the videotutorial.
{
"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