Unleashing HMS ADs kit: with React Native - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum
Advertisement: Buzz word in today’s era
{
"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 journey from newspaper advertisement to digital advertisement is been beautiful as we understand the need of advertisement in any business.
Every business focuses on exponential growth and profits and hence advertisement plays vital role in it.
HMS ADS KIT provides easy and powerful solution for enabling the business growth and monetize the services.
HMS ADS KIT offers a range of different ad formats for different business needs as following
Banner Ads
Native Ads
Interstitial Ads
Rewarded Ads
Splash Ads
Banner Ads
Banner advertising refers to the use of a rectangular graphic display that stretches across the top, bottom, or sides of a website or online media property.
The purpose of banner advertising is to promote a brand and/or to get traffic from the host page to go to the advertiser's website.
“The first banner advertisement was deployed on Wired Magazine's website in 1994”
​
As HMS Ads kit offers range of ads format, will elaborate how does banner ads work using the HMS solution.
Development Overview
HMS Ads KIT can be integrated for various business requirements in your react native project as following:
Perquisites
· Must have a Huawei Developer Account
· Must have a Huawei phone with HMS 4.0.0.300 or later
· React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
· React Native CLI : 2.0.1
· Gradle Version: 6.0.1
· Gradle Plugin Version: 3.5.2
· React Native Site Kit SDK : 4.0.4
· React-native-hms-site gradle dependency
· AGCP gradle dependency
Preparation
In order to develop the HMS react native apps following steps are mandatory.
· First, we need to create an app or project in the Huawei app gallery connect.
· Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
· Create a react native project. Using
Code:
“react-native init project name”
Tip: agconnect-services.json is not required for integrating the hms-ads-sdk.
· Download the React Native Ads Kit SDK and paste It under Node modules directory of React Native project.
Tip: Run below command under project directory using CLI if You cannot find node modules.
Code:
“npm install”
“npm link”
Integration
· Configure android level build.gradle
1. Add to buildscript/repositores
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Add to allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
· Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“:react-native-hms-ads”)
· Linking the HMS Ads Kit Sdk
1) Run below command in the project directory
Code:
react-native link react-native-hms-ads
Adding permissions
Add below permissions to Android.manifest file.
Code:
1. <uses-permission android:name="android.permission.INTERNET" />
2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development Process
HMS Ads SDK already provides the code for all the supported ads format.
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
Code:
import {
HMSBanner,
BannerAdSizes,
ContentClassification,
Gender,
NonPersonalizedAd,
TagForChild,
UnderAge,
} from 'react-native-hms-ads';
Declare bannerAdId in App.js file
AdId is ad slot id which can be generated using Publisher service
Code:
const Banner = () => {
let bannerAdIds = {};
bannerAdIds[BannerMediaTypes.IMAGE] = 'testw6vs28auh3';
Define supported ads size
Code:
const [bannerAdSize, setBannerAdSize] = useState({
bannerAdSize: BannerAdSizes.B_320_100,
// width: 0,
});
Create a function to define the banner ad and its elements with load and failed case
Code:
<HMSBanner
style={{height: 100}}
bannerAdSize={bannerAdSize}
adId={adId}
adParam={{
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: '',
}}
// function to load the above banner add on the button click
[/CODE]onAdLoaded={(e) => {
console.log('HMSBanner onAdLoaded', e.nativeEvent);
toast('HMSBanner onAdLoaded');
}}[/CODE]
//function to handle failed ad loading on button click
Code:
onAdFailed={(e) => {
console.warn('HMSBanner onAdFailed', e.nativeEvent);
toast('HMSBanner onAdFailed');
}}
//Display text accordingly on below functions
Code:
onAdOpened={(e) => toast('HMSBanner onAdOpened')}
onAdClicked={(e) => toast('HMSBanner onAdClicked')}
onAdClosed={(e) => toast('HMSBanner onAdClosed')}
onAdImpression={(e) => toast('HMSBanner onAdImpression')}
onAdLeave={(e) => toast('HMSBanner onAdLeave')}
// component reference
Code:
ref={(el) => {
adBannerElement = el;
}}
/>
Results
Conclusion
Adding banner ads seem very easy. Stay tuned for more ads activity.

Related

Amalgamating HUAWEI NATIVE ADs: 21st CENTURY PLACARD : feat. React Native

More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201327829880650040&fid=0101187876626530001
{
"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"
}
“Native advertising”, a term first coined by Fred Wilson at the Online Media, Marketing, and Advertising Conference in 2011.Native advertising is a form of paid media where the ad experience follows the natural form and function of the user experience in which it is placed.
Huawei Ads Kit offers variety of different ads format to reach the consumer marketing goals in today’s competitive world.
Huawei Ads Kit demonstrate an easy and efficient way to implement the native 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.
Adding a Native Ad
Configuring Properties
Executing Commands
Testing
HMS Native Ads aligned with the application and device layout seamlessly, however these can be customised as well.
Adding a Native Ad
HMSNative module is added to the application to work with native ads components. Height can also be customized with the help of ‘style’.
Code:
import {
HMSNative,
} from'react-native-hms-ads';
style={{height:322}}/>
Configuring Properties
Native Ads properties can be configured in various ways
1. For handling different media types, create different ads slot id for different media type ads.
2. Custom listeners can also be added to listen different events
3. Specific native ads can be implemented and requested to target specific audience.
4. Position of the ads component can customized and adjusted
5. View options for the texts on the native ad components can also be changed.
Import below modules for customizing the native ads as required.
Code:
import {
HMSNative,
NativeMediaTypes,
ContentClassification,
Gender,
NonPersonalizedAd,
TagForChild,
UnderAge,
ChoicesPosition,
Direction,
AudioFocusType,
ScaleType
} from'react-native-hms-ads';
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
Create a function in the app.js file as below and add the ad slot id.
Code:
const Native = () => {x
let nativeAdIds = {};
nativeAdIds[NativeMediaTypes.VIDEO] = 'testy63txaom86';
nativeAdIds[NativeMediaTypes.IMAGE_SMALL] = 'testb65czjivt9';
nativeAdIds[NativeMediaTypes.IMAGE_LARGE] = 'testu7m3hc4gvm';
Code:
//Setting up the media type
const [displayForm, setDisplayForm] = useState({
mediaType: NativeMediaTypes.VIDEO,
adId: nativeAdIds.video,
});
Code:
//Add below code for different configuration
nativeConfig={{
choicesPosition: ChoicesPosition.BOTTOM_RIGHT,
mediaDirection: Direction.ANY,
// mediaAspect: 2,
// requestCustomDislikeThisAd: false,
// requestMultiImages: false,
// returnUrlsForImages: false,
// adSize: {
// height: 100,
// width: 100,
// },
videoConfiguration: {
audioFocusType: AudioFocusType.NOT_GAIN_AUDIO_FOCUS_ALL,
// clickToFullScreenRequested: true,
// customizeOperateRequested: true,
startMuted: true,
},
}}
viewOptions={{
showMediaContent: false,
mediaImageScaleType: ScaleType.FIT_CENTER,
// adSourceTextStyle: {color: 'red'},
// adFlagTextStyle: {backgroundColor: 'red', fontSize: 10},
// titleTextStyle: {color: 'red'},
descriptionTextStyle: {visibility: false},
callToActionStyle: {color: 'black', fontSize: 12},
}}
Executing Commands
To load the ad on the button click, loadAd() api is used.
Code:
title="Load"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.loadAd();
}
}}
To dislike the ad on the button click, dislikeAd() api is used.
Code:
title="Dislike"
color="orange"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.dislikeAd('Because I dont like it');
}
}}
To allow the click on the ad setAllowCustomclick() api is used on te button click.
Code:
title="Allow custom click"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.setAllowCustomClick();
}
}}
To Report an ad impression on the button click.
Code:
title="Record impression"
color="red"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.recordImpressionEvent({
impressed: true,
isUseful: 'nope',
});
}
}}
To navigate through the ‘why’page, gotowhyThisAdPage() api is used.
Code:
title="Go to Why Page"
color="purple"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.gotoWhyThisAdPage();
}
}}
To record an event on the button click recordClickEvent() api is used.
Code:
title="Record click event"
color="green"
onPress={() => {
if (adNativeElement !== null) {
adNativeElement.recordClickEvent();
}
}}
Below listeners are implemented to start, play and stop the video ads.
Code:
onVideoStart={(e) => toast('HMSNative onVideoStart')}
onVideoPlay={(e) => toast('HMSNative onVideoPlay')}
onVideoEnd={(e) => toast('HMSNative onVideoEnd')}
Testing
Run the below command to build the project
Code:
React-native run-android
After successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
Conclusion
Adding Native ads seem very easy. Stay tuned for more ads activity.

Elucidating HMS Splash Ads : Feat. React Native

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.

An Introduction of HMS In-App Purchase in Ionic Application ( Cross Platform Integration )

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
​

An elucidation to Huawei React Native Scan Kit Plugin(Cross platform support)

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

Everything is just a scan way! Integration of Huawei Scan Kit in Books Applications

{
"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

Categories

Resources