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