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.
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=0202333954713070046&fid=0101187876626530001
A Splash Ad is called Splash Ad because it is a full page interstitial ad that is displayed immediately after the application is launched.
A Splash Ad first displays a full-page splash screen that you define (for example your app's logo or branding) followed by a full page ad.
Huawei Ads kit offers Splash Ad to use in your business to achieve certain business and advertisement goals by following the digital marketing practices.
Huawei Ads Kit demonstrate an easy and efficient way to implement the splash ads within your application.
Prerequisite
1. Must have a Huawei Developer Account
2. Must have a Huawei phone with HMS 4.0.0.300 or later
3. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
1. React Native CLI : 2.0.1
2. Gradle Version: 6.0.1
3. Gradle Plugin Version: 3.5.2
4. React Native Site Kit SDK : 4.0.4
5. React-native-hms-site gradle dependency
6. AGCP gradle dependency
Development Overview
Preparation
1. Create an app or project in the Huawei app gallery connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project, use the below command
“react-native init project name”
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
Tips
1. agconnect-services.json is not required for integrating the hms-ads-sdk.
2. Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle. (Add to dependencies)
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Ads Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-ads
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
· Creating a Splash Ad
· Setting Ad Slot ID
· Customizing Splash Screen
· Setting Ad Request Parameters
· Display Ad
· Listen to Ad Events
· Testing
HMS Splash Ads aligned with the application and device layout seamlessly, however these can be customised as well.
Creating a Splash Ad
HMSSplash component needs to be added to import the Splash ads in the code.
Code:
import {HMSSplash} from 'react-native-hms-ads';
Setting Ad Slot ID
setAdId() is the method used for creating an ad slot ID reference to the app.js file.
Code:
HMSSplash.setAdId("AdSlotId");
Where AdSlotId = "testd7c5cewoj6" and can also be defined as Video or Image media types
Note
Developers can use publisher services to create the Ad Slot ID. Refer this article to know the process for creating the slot Id’s
Customizing Splash Screen
Splash ads can also be customized as explained below.
Create a function in app.js file and add different customizations.
Changing the logo text or setting up the copy write text to your advertisement.
Code:
HMSSplash.setLogoText('HMS App');
HMSSplash.setCopyrightText('Copyright HMS');
Setting Ad Request Parameters
setAdParam() is used to set the set the additional parameters to get specific ads for specific audience. Below code can be executed on the button click to ad additional parameters.
Code:
import {ContentClassification,UnderAge } from 'react-native-hms-ads';
HMSSplash.setAdParam({
adContentClassification:
ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
// appCountry: '',
// appLang: '',
// belongCountryCode: '',
gender: Gender.UNKNOWN,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
// requestOrigin: '',
tagForChildProtection:
TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
// targetingContentUrl: '',
}
Display Ad
Show() method is used to display the ads on the button click.
Code:
<Button title="Splash" color="green" onPress={() => HMSSplash.show()}/>
Listen to Ad Events
Listener functions can be triggered with the different ad actions and associated events.
Code:
HMSSplash.adLoadedListenerAdd(() => {
toast('HMSSplash adLoaded');
});
// HMSSplash.adLoadedListenerRemove();
HMSSplash.adFailedToLoadListenerAdd(() => {
toast('HMSSplash adFailedToLoad');
});
// HMSSplash.adFailedToLoadListenerRemove();
HMSSplash.adDismissedListenerAdd(() => {
toast('HMSSplash adDismissed');
});
// HMSSplash.adDismissedListenerRemove();
HMSSplash.adShowedListenerAdd(() => {
toast('HMSSplash adShowed');
});
// HMSSplash.adShowedListenerRemove();
HMSSplash.adClickListenerAdd(() => {
toast('HMSSplash adClick');
});
Testing
Run the below command to build the project
Code:
React-native run-android
Upon successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
References
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050196714
Conclusion
Adding Splash Ads seems very easy.
Introduction
In this article, I will talk about that how Flutter project integrates Huawei kits, and learn how to use them in your Flutter projects. Apps are tested many times before they released, but still crashes are there. There is a Huawei Crash Service to minimize these risks. Learning app which highlights recommended courses and Topic based courses, here I will cover below kits.
1. IAP kit
2. Crash Service
Requirements
1. Any operating system (i.e. MacOS, Linux and Windows).
2. Any IDE with Flutter SDK installed (i.e. IntelliJ, Android Studio and VsCode etc.).
3. A little knowledge of Dart and Flutter.
4. Minimum API Level 24 is required.
5. Required EMUI 5.0 and later version devices.
Setting up the Project
1. First create a developer account in AppGallery Connect. After create your developer account, you can create a new project and new app. For more information, click here
2. Generating a Signing certificate fingerprint, follow the command
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
3. The above command creates the keystore file in appdir/android/app.
4. Now we need to obtain the SHA256 key. Follow the command
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
5. Now you need to apply for merchant service and enable IAP. To enable Merchant Service, Choose My Projects > Manage APIs > In-App Purchases. You will be asked to apply for Merchant Service. Here, you’ll need to enter your bank information and go through a review process. This review process can take up to 2 days.
{
"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"
}
6. Once Merchant service activated, Navigate to Earning > In-App Purchases if this is the first time, then you need to sign the agreement.
7. After the configuration is successful, the page displays the public key used for subsequent payment signature verification and a parameter for configuring the subscription notification URL.
8. We need Sandbox account in order to test the IAP. Navigate to App Gallery > Users and Permissions > Sandbox >Test account.
9. We have to enable Analytics to use Crash Service. Navigate to App Gallery > Huawei Analytics. The Analytics page is displayed.
10. We have to enable the Crash service, Navigate to Quality > Crash and enable Crash service.
11. After configuring project, we need to download agconnect-services.json file in your project and add into your project.
12. After that follow the URL for cross-platform plugins. Download required plugins.
13. The following dependencies for HMS usage need to be added to build.gradle file under the android directory.
Code:
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
}
14. Add the below plugin in build.gradle file under the android/app directory.
Code:
apply plugin: 'com.huawei.agconnect'
15. Add the required permissions in AndroidManifest.xml file under app/src/main folder.
XML:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
16. After completing all the above steps, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
huawei_iap:
path: ../huawei_iap/
agconnect_crash: ^1.1.0
After adding them, run flutter pub get command. Now all the plugins are ready to use.
Note: Set multiDexEnabled to true in the android/app directory, so that app will not crash.
IAP Kit Introduction
In-app purchases can be used to sell a variety of content through your app, including subscriptions, new features, and services. Users can make in-app purchases on all sorts of devices and operating systems — not just their mobile phones.
There are 4 types of in-app purchases available in Huawei IAP Kit.
Consumables: Users can purchase different types of consumables, such as extra lives or gems in a game, to further their progress through an app. Consumable in-app purchases are used once, are depleted, and can be purchased again.
Non-Consumables: Users can purchase non-consumable, premium features within an app, such as additional filters in a photo app. Non-consumables are purchased once and do not expire.
Auto-Renewable Subscriptions: Users can purchase access to services or periodically updated content, such as monthly access to cloud storage or a weekly subscription to a magazine. Users are charged on a recurring basis until they decide to cancel.
Non-Renewing Subscriptions: Users can purchase access to services or content for a limited time, such as a season pass to streaming content. This type of subscription does not renew automatically, so users need to renew at the end of each subscription period.
How to Configure Product info
To add product, Navigate to My Apps > Learning app > Operate > Product operation > Product management. Click Products tab and click Add product. Configure Product information and click Save.
Now we successfully added consumable products, we need to activate the product.
Let’s implement code
First we need to check whether environment and sandbox account is ready.
YAML:
checkEnv() async {
isEnvReadyStatus = null;
try {
IsEnvReadyResult response = await IapClient.isEnvReady();
isEnvReadyStatus = response.status.statusMessage;
if (isEnvReadyStatus != null) {
checkSandboxAccount();
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
print(HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
print(e.toString());
}
}
}
checkSandboxAccount() async {
isSandBoxStatus = null;
try {
IsSandboxActivatedResult result = await IapClient.isSandboxActivated();
isSandBoxStatus = result.status.statusMessage;
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
print(HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
print(e.toString());
}
}
}
Fetch products
Use the obtainProductInfo API to get details of in-app products configured in AppGallery Connect.
Perform the following development steps
Construct a ProductInfoReq object to get ProductInfo.
Pass the Product ID that was defined and effective in AppGallery Connect to the ProductInfoReq object and specify the priceType for a product
YAML:
fetchConsumable() async {
try {
ProductInfoReq req = new ProductInfoReq();
req.priceType = IapClient.IN_APP_CONSUMABLE;
req.skuIds = ["ED_1011"];
ProductInfoResult res = await IapClient.obtainProductInfo(req);
consumable = [];
for (int i = 0; i < res.productInfoList.length; i++) {
consumable.add(res.productInfoList[i]);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
print(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
print(e.toString());
}
}
}
Purchase products
You can initiate a purchase request through the createPurchaseIntent API. Call createPurchaseIntent with the appropriate parameters to automatically display the HUAWEI IAP payment page.
YAML:
subscribeProduct(String productID) async {
PurchaseIntentReq request = PurchaseIntentReq();
request.priceType = IapClient.IN_APP_CONSUMABLE;
request.productId = productID;
request.developerPayload = "Course";
try {
PurchaseResultInfo result = await IapClient.createPurchaseIntent(request);
if (result.returnCode == HmsIapResults.ORDER_STATE_SUCCESS.resultCode) {
log("Successfully plan subscribed");
} else if (result.returnCode ==
HmsIapResults.ORDER_STATE_FAILED.resultCode) {
log("Product subscription failed");
} else if (result.returnCode ==
HmsIapResults.ORDER_STATE_CANCEL.resultCode) {
log("User cancel the payment");
} else if (result.returnCode ==
HmsIapResults.ORDER_PRODUCT_OWNED.resultCode) {
log("Already Product subscribed");
} else {
log(result.errMsg);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}
Crash Service Introduction
This service help us to minimize these crash risks. Also this service integration is relatively simple and doesn’t require coding. The Crash Service provides crash reports which are easy to reference and analyze.
Huawei Crash Service provides a powerful yet lightweight solution to app crash problems. With the service, you can quickly detect, locate, and resolve app crashes (unexpected exits of apps), and have access to highly readable crash reports in real time, without the required to write any code.
Crash Service provides some various features
1. The last-hour crash report allows you to monitor the quality of your app in real time.
2. The Crash service automatically categorizes crashes, and provides indicator data of the crashes allowing you to prioritize the most important crashes.
3. You can view information about a specific crash, and analyze the app and Android versions with the crash.
4. You can also view information about the app, operating system, and device corresponding to a specific crash, as well as the crashed stack.
5. The Crash service can also detect major crashes in real time. After you enable crash notifications, App Gallery Connect can send you an email when a major crash occurs.
To create a crash we have a AGCCrash.instance().testIt() method. By calling it we can crash our app. On button click add this method and crash your app
Code:
Positioned(
top:30,
child: Container(
child: IconButton(
onPressed: (){
AGCCrash.instance.testIt();// To test crash
},
icon: Icon(Icons.arrow_back,color: Colors.white,),
),
),
)
We also have custom report methods such as setUserId, log, setCustomValue and so on. In this example I created a test button Custom Report in ViewController class. You can click the button to call the setUserId method to set the user ID, the log:level method to record logs, and the setCustomValue:value method to add custom key-value pairs.
Code:
void handleCrash() async{
await AGCCrash.instance.enableCrashCollection(true);
AGCCrash.instance.setUserId("11223344");
AGCCrash.instance.setCustomKey("Huawei", "Reporting crashed"); AGCCrash.instance.log(level: LogLevel.debug,message: "Crash has successfully reported.");
}
How we can check crash Report
Crash Service automatically reports the occurred crashes to AppGallery Connect. Details and the cause of crash can also be viewed in the statistics page on AppGallery Connect.
How to access to the Crash Service Page:
Navigate to Quality > Crash. The Crash page is displayed.
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. Do not forget to create sandbox account.
3. Do not forget to click pug get after adding dependencies.
4. Latest HMS Core APK is required.
Conclusion
In this article, we have learnt integration of Huawei Iap kit, Crash service into Flutter project.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference
In-App Purchase Kit URL
Crash service URL
Original Source
These days, the smart watch market is highly competitive. Watches no longer just tell us the time, rather they can allow us to take and make calls, scan barcodes, check our location, and perform a variety of other functions. They are particularly useful for vulnerable groups such as children and elderly people, which has opened new doors for businesses. Huawei's HarmonyOS-powered watch is one such device that aims to create an intelligent user experience. It does this by leveraging the capabilities of HMS Core Location Kit, which are: fused location, activity identification, and geofence. In this article, I'll show you how the location function on HarmonyOS watches works, through several simple steps.
Advantages and Restrictions of Location Kit1. It implements the geofence function based on chips, saving power.
2. It improves roadside location accuracy in urban canyons, and implements location accurate to less than a meter in open areas based on the Real-time Kinematic (RTK) technology.
3. The latest Location SDK can be used only on devices running HMS Core (APK) 6.0.0 or later. If HMS Core (APK) is not installed or its version is earlier than 6.0.0, the SDK functions properly but cannot be automatically updated.
4. To ensure app integrity, HarmonyOS uses a digital certificate and a profile to ensure that only packages with signed HarmonyOS Ability Package (HAP) files can be installed on devices.
Demo IntroductionI have provided a simple demo here. You can use the demo to experience how to implement location on HarmonyOS watches. The demo includes requesting location updates, obtaining the cached location, checking whether the location is available, and checking and setting the location permissions.
Integration ProcedureI'll now show you how to run the demo using source code, so that you can understand how it is implemented.
Preparations1. Preparing Tools
Test device: a Huawei smart watch running HarmonyOS 2.0 or later
Development tool: DevEco Studio 2.1.0.201 or later
2. Preparing for the Development
(1) Register as a Huawei developer and create an app. Refer to the Location Kit Development Preparations to create an app in AppGallery Connect.
(2) Generate a digital certificate and profile. This requires you to apply for an app debugging certificate, register a debugging device, apply for a debugging profile, and configure signature information.
(3) Generate a signing certificate fingerprint and configure it.
(4) Integrate the Location SDK.
Download the agconnect-services.json file from AppGallery Connect, and place it in the entry\src\main\resources\rawfile directory.
Add apply plugin: 'com.huawei.agconnect' as a line under the file header declaration, and add the Maven repository address and a dependency on the AppGallery Connect service in the project-level build.gradle file.
Java:
buildscript {
repositories {
maven {url 'https://repo.huaweicloud.com/repository/maven/'}
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
jcenter()
}
dependencies {
classpath 'com.huawei.ohos:hap:2.4.4.2'
// Add a dependency on the AppGallery Connect service.
classpath 'com.huawei.agconnect:agcp-harmony:1.1.0.300'
classpath 'com.huawei.ohos:decctest:1.2.4.0'
}
}
allprojects {
repositories {
maven {url 'https://repo.huaweicloud.com/repository/maven/'}
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
jcenter()
}
}
Add a dependency in the app-level build.gradle file. You can replace the version number as needed.
Java:
dependencies {
implementation 'com.huawei.hms:location-ohos:6.0.0.300'
// Add a dependency on AppGallery Connect.
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.1.0.300'
}
If you need to configure obfuscation, open the obfuscation configuration file proguard-rules.pro in the app's root directory of your project and add configurations to exclude the HMS Core SDK from obfuscation.
The figure below shows the demo effect.
{
"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"
}
Key Steps1. Declare required permissions in reqPermissions in the config.json file.
HarmonyOS provides two types of location permissions: ohos.permission.LOCATION (location permission) and ohos.permission.LOCATION_IN_BACKGROUND (background location permission). Note that network permission is also required.
Java:
"reqPermissions": [
{
"reason": "get Local Location",
"name": "ohos.permission.LOCATION",
"usedScene": {
"ability": [
"com.huawei.codelab.MainAbility",
],
"when": "always"
}
},
{
"name": "ohos.permission.GET_NETWORK_INFO"
},
{
"name": "ohos.permission. LOCATION_IN_BACKGROUND"
}
2. Dynamically apply for the ohos.permission.LOCATION and ohos.permission.LOCATION_IN_BACKGROUND permissions in the code.
Java:
/The following uses the location permission as an example.
if (verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) {
printLog(HiLog.INFO, TAG, "Self: LOCATION permission not granted!");
if (canRequestPermission("ohos.permission.LOCATION")) {
printLog(HiLog.INFO, TAG, "Self: can request permission here");
requestPermissionsFromUser(
new String[]{"ohos.permission.LOCATION"}, REQUEST_CODE);
} else {
printLog(HiLog.WARN, TAG, "Self: enter settings to set permission");
}
} else {
printLog(HiLog.INFO, TAG, "Self: LOCATION permission granted!");
}
Key Code1. Create a location service client.
Create a FusedLocationProviderClient instance in the onStart() method of BaseAbilitySlice, and use this instance to call location-related APIs.
Java:
public FusedLocationProviderClient fusedLocProviderClient;
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
fusedLocProviderClient = new FusedLocationClient(this);
}
2. Check the device location settings.
Call LocationRequest to set location request parameters, including the location update interval (in milliseconds), weight, and location information language. Before requesting callback, call the location service to check location settings.
Java:
private void checkLocationSettings() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setPriority(100);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
LocationSettingsRequest request =
builder.addLocationRequest(locationRequest).setAlwaysShow(false).setNeedBle(false).build();
settingsClient.checkLocationSettings(request)
.addOnSuccessListener(response -> {
// Device location settings meet the requirements.
})
.addOnFailureListener(exp -> {
// Device location settings do not meet the requirements.
});
}
3. Implement the location function.
Call requestLocationUpdates() for continuous location.
Java:
fusedLocProviderClient.requestLocationUpdates(locationRequest, locationCallback)
.addOnSuccessListener(var -> {
// Processing when the API call is successful.
})
.addOnFailureListener(e -> {
// Processing when the API call fails.
});
Call removeLocationUpdates() to stop requesting location updates.
Java:
// Note: When location updates are stopped, the mLocationCallback object must be the same object as LocationCallback in the requestLocationUpdates() method.
fusedLocProviderClient.removeLocationUpdates(locationCallback)
.addOnSuccessListener(var -> {
// Processing when the API call is successful.
})
.addOnFailureListener(e -> {
// Processing when the API call fails.
});
Define the location update callback.
Java:
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
// Process the location callback result.
}
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
super.onLocationAvailability(locationAvailability);
if (locationAvailability != null) {
// Process the location status.
}
}
};
Related Parameters1. Parameter for setting the location type. The options are as follows:
100: GNSS location
102 or 104: network location
105: indicates that locations are being received passively as opposed to being requested proactively.
2. Parameter for setting the location language. Currently, the options include only EN and CN.
3. Parameter for setting the number of location updates (setNumUpdates). If the value is 3, the app will receive three location updates. To continuously receive location updates, you are advised to use the default value.
References>> Location Kit official website
>> Location Kit Development Guide
>> Reddit to join developer discussions
>> GitHub to download the sample code
>> Stack Overflow to solve integration problems
{
"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 Auth Service in an Application. The Auth Service SDK into our app, we can easily and quickly provide functions such as registration and sign-in for our users. We can choose to provide our users with one or more of the authentication modes like Mobile number, Email address, Facebook, WeChat etc. We will integrate the authentication by Facebook into the app, so that our users can use Facebook to sign in to the app securely,
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, as follows.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
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 the React Native Account Kit SDK and paste it under Node Modules directory of React Native project. If you cannot find node modules run below command under project directory using CLI.
“npm install” & “npm link”
11. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
12. Configure app level build.gradle. (Add to dependencies)
Implementation project (“:react-native-hms-account”)
13. Linking the HMS Account Kit Sdk.
Run below command in the project directory
Code:
react-native link react-native-hms-account
14. Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
15. Enabling Auth Service
(i). Sign in to AppGallery Connect and click My projects.
(ii). Click a project that you want to enable Auth Service from the project list.
(iii). Choose Build > Auth Service. If it is the first time that you use Auth Service, click Enable now in the upper right corner.
(iv). Click Enable in the row of each authentication mode to be enabled.
For more details visit this documentation.
Development
On the app sign-in page, obtain user information from AppGallery Connect, and check whether a user has signed in. If a user has signed in, the user's home page is displayed; if no user has signed in, the sign-in page is displayed.
After a user requests to sign in using a Facebook account, obtain the user authorization information of the account.
Call FacebookAuthProvider.credential to generate a credential using the access token obtained from the Facebook account, and then call AGCAuth.signIn to implement sign-in.
JavaScript:
let credential = FacebookAuthProvider.credential("accessToken");
AGCAuth.getInstance()
.signIn(credential)
.then((signInResult) => {
// signInResult.user to get user info
})
.catch((error) => {
// error
});
Homepage.js
JavaScript:
const [list, setList] = useState([])
const [value, setValue] = useState("")
// A function that add data to the list array
function addText(text) {
if (value !== "") {
setList(prev => {
return [
...prev,
{ text: text, isSelected: false } // Adding a JS Object
]
})
setValue("")
} else {
alert("Please type in something!")
}
}
// A function that set the value of isSelected based on the state of the checkbox
function setIsSelected(index, value) {
let data = []
// Making a deep copy of the list array
for (let i = 0; i < list.length; i++) {
if (index === i) {
data.push({ ...list[i], isSelected: value }) // Updating the object at position i === index
} else {
data.push(list[i])
}
}
setList(data) // Setting the new state
}
// A function that delete an item at position idx from the list array
function deleteItem(idx) {
Alert.alert(
"Delete Item",
"Are you sure you want to delete this item?",
[
{
text: "Cancel",
style: "cancel"
},
{
text: "Yes", onPress: () => {
const data = list.filter((item, index) => index !== idx)
setList(data)
}
}
])
}
return <View style={styles.container}>
<Text style={{ ...FONTS.h1_semiBold, color: COLORS.secondary, marginBottom: 15 }}>What needs to be done.</Text>
<FlatList style={{ flex: 1 }}
data={list}
renderItem={({ item, index }) => <Card data={item} index={index} setIsSelected={setIsSelected} deleteItem={deleteItem} />}
keyExtractor={(item, index) => index.toString()}
/>
<View style={styles.textBoxWrapper}>
<TextInput
style={styles.textInput}
placeholder="New Task"
placeholderTextColor={COLORS.primary}
onChangeText={text => setValue(text)}
value={value} />
<TouchableOpacity
style={styles.btn}
onPress={() => addText(value)}>
<Text style={{ fontSize: 34, color: COLORS.secondary }}>+</Text>
</TouchableOpacity>
</View>
</View>
Testing
Run the android App using the below command.
Code:
react-native run-android
Result
Conclusion
In this article, we have learnt that how to integrate the Facebook authentication mode into the app, so that our users can use Facebook to sign in to the app securely.
Reference
Account Kit: Documentation
Account Kit: Training Video