Integrating HUAWEI In-app message with Google In-app message in single Application - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum​
Introduction
In-App Messaging helps you engage your app's active users by sending targeted, contextual messages that encourage to use key app features. For example, you could send an in-app message to get users to subscribe, watch a video, complete a level, or buy an item. You can customize messages as cards, banners, modals, or images, and set up triggers so that they appear exactly when benefit your users most.
Usecase
1. Add following image on Huawei App gallery connect console and google firebase console to be shown as in-app message in our app.
{
"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"
}
2. App installed on Huawei device will fetch in-app message (image) from Huawei App gallery connect.
3. App installed on GMS devices will fetch in-app message (image) from Google firebase console.
Huawei In-App Messaging
Prerequisite
1. You must have Huawei developer account.
2. Huawei phone with HMS 4.0.0.300 or later
3. Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Setup:
1. Create a project in android studio.
2. Get the SHA-256 Key.
3. Create an app in the Huawei app gallery connect.
4. Enable account kit setting in Manage APIs section.
5. Provide the SHA-256 Key in App Information Section.
6. Provide storage location.
7. After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in   the app folder of the android project.
8. Enter the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file )
Code:
maven { url 'http://developer.huawei.com/repo/' }
9. Enter the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
10. Put the below permission in AndroidManifest file.
  a) android.permission.INTERNET
  b) android.permission.ACCESS_NETWORK_STATE
11. Now Sync the gradle.
Implemetation
1. We need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
2. Add following code in your project to obtain AAID
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
3. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
4. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
5. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
6. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Creating Image In-App Messaging on App Gallery connect
1. Sign in to AppGallery Connect and select My projects.
2. Select your project from the project list.
3. Navigate Growing > App Messaging and click New.
4. Set Name and Description for your in-app message.
5. Provide the in-app message Type. For image in-app message, select type as Image.
6. Provide image URL.
7. Provide the action for image tapping.
8. Click next to move on to the next section, that is, Select Sending Target section. Here we can define Condition for matching target users. In this article, we did not use any condition.
9. The next section is the Set Sending Time section.
We can schedule a date and time to send in-app message.
We can also provide an End date and time to stop sending message.
We can also display message on an events by using trigger event functionality. For example, we can display a discount of an item in a shopping app. A trigger event is required for each in-app message.
Also we can flexibly set the frequency for displaying the in-app message.
10. Click Next, find Set conversation events. It associates the display or tap of the app message with a conversion event. The conversion relationship will be displayed in statistics. As off now we will keep it as none.
11. Click Save in the upper right corner to complete message creation.
12. In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. Find the message that you need to test, and click Test in the Operation column as shown below:
13. Provide the AAID of the test device in the text box. Click Save.
14. Click Publish.
Google firebase In-App Messaging
Steps:
1. To enable Firebase in your app, add following lines in your root-level build.gradle file.
Code:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
2. In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin:
Code:
apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}
3. To your module (app-level) Gradle file (usually app/build.gradle), add the dependencies.
Code:
dependencies {
// Add the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics:17.4.4'
implementation 'com.google.firebase:firebase-auth:19.3.2'
}
4. That testing device is determined by a FirebaseInstallations ID, or FID. Find your testing app's FID by checking the Logcat in Android Studio for the following `Info` level log:
Code:
I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID YOUR_INSTALLATION_ID
We will add this FID while composing in-app message on firebase console.
5. Set up your new campaign in the Firebase consoles Firebase In-App Messaging page.
6. Select your project and click Create a new campaign.
7. In this article, we will use image in-app message. Select message layout as Image only. Provide Image URL and click Next.
8. Provide campaign name and description and define your target user. Here we have not defined any target user.
9. Click Next to define campaign start time, end time, trigger event and frequency limit of in-app message.
10. Click Next and provide conditional events and additional options. These are optional. Click Save as draft.
11. Select Test on Device, and add the earlier generated FID.
12. Run the application on GMS installed device, you will see Google in-app message.
To check if device has HMS or GMS installed
Code:
public class Utils {
public static boolean isSignedIn = false;
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}
public static boolean isDeviceHuaweiManufacturer () {
String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;
}
}
References:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-appmessage-introduction
https://firebase.google.com/docs/in-app-messaging/get-started?platform=android

Related

Recipe To Integrate In-App Messaging In 10 Minutes

This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
{
"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"
}
HMS In-App Messaging is a tool to send relevant messages to target users actively using our app to encourage them to use key app functions. For example, we can send in-app messages to encourage users to subscribe to certain products, provide tips on passing a game level, or recommend activities of a restaurant.
In-App Messaging also allow us to customize our messages, the way it will be sent and also define events for triggering message sending to our users at the right moment.
Today I am going to server you a recipe to integrate In-App Messaging in your apps within 10 minutes.
Key Ingredients Needed
· 1 Android App Project, which supports Android 4.2 and later version.
· 1 SHA Key
· 1 Huawei Developer Account
· 1 Huawei phone with HMS 4.0.0.300 or later
Preparation Needed
· 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 android project in App Information Section.
· Provide storage location in convention section under project setting.
· Enable App Messaging setting in Manage APIs section.
· After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the json file in the app folder of the android project.
· Copy and paste the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file)
Code:
maven { url 'http://developer.huawei.com/repo/' }
· Copy and paste the below class path inside the dependency section of project build.gradle file.
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
· Copy and paste the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
· Copy and paste below library in the app build.gradle file dependencies section
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.3.1.300'
· Put the below permission in AndroidManifest file.
  a) android.permission.INTERNET
  b) android.permission.ACCESS_NETWORK_STATE
· Now Sync the gradle.
Android Code
1. First we need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
2. Add following code in your project to obtain AAID:
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
3. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
4. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
5. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
6. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Till now we added libraries, wrote the code in android studio using java etc. in the heated pan and the result will look like this:
Code:
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private AGConnectAppMessaging appMessaging;
private HiAnalyticsInstance instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(this);
instance.setAnalyticsEnabled(true);
instance.regHmsSvcEvent();
inAppMessaging();
}
private void inAppMessaging() {
appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
}
App Gallery Connect
Before we start using one of our key ingredients i.e. Huawei App Gallery Connect using Huawei Developer Account to serve In-App Messages, I would like to inform you that we can server the main dish into three different flavour or types:
A. Pop-up Message Flavour
B. Banner Message Flavour
C. An Image Message Flavour
In-App Message Using Pop-up Flavour
Let’s serve the main dish using Pop-up Message Flavour.
Step 1: Go to Huawei App Gallery Connect
Step 2: Select My projects.
Step 3: After selecting my projects, select the project which we have create earlier. It will look like this:
Step 4: After selecting the project, we will select App Messaging from the menu. It will look like this:
Step 5: Select New button to create new In-App Message to send to the device.
Step 6: Provide the Name and Description. It will look like this:
Step 7: In the Set style and content section, we have to select the type (which is Pop-up), provide a title, a message body, and choose colour for title text, body text and the background of the message. It will look like this:
Step 8: After providing the details in set style and content section, we will move on to the Image section. We will provide two image here for portrait and landscape mode of the app. Remember for portrait the image aspect ratio should be 3:2 (300x200) and for landscape the image aspect ratio should be either 1:1 (100x100) or 3:2 (300x200). It will look like this:
https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200512212645.95630192255042904397797509198276:50510525101557:2800:FA1CFD7E5EA43100725399BB4787A4B9FB44B8E02776FF83D09816D732E0AA63.png​
Step 9: We can also provide a button in the Pop-up message using Button Section. The button contains an action. This Action contains two option. We can provide user with Disable Message action or redirect user to particular URL. The section will look like this:
Step 10: We will now move to the next section i.e Select Sending Target section. Here we can click New condition to add a condition for matching target users. Condition types include app version, OS version, language, country/region, audience, user attributes, last interaction, and initial startup.
Note: In this article, we didn’t used any condition. But you are free to use any condition to send targeted In-App Messages.
The section will look like this:
Step 11: The next section is the Set Sending Time section.
a) We can schedule a date and time to send message.
b) We can also provide an End date and time to stop sending message.
c) We can also display message on an events by using trigger event functionality. For example, we can display a discount of an item in a shopping app. A trigger event is required for each in-app message.
d) Also we can flexibly set the frequency for displaying the message.
This is how it will look:
Step 12: The last section is the Set Conversion Event section. As off now we will keep it as none. It will look like this:
Step 13: Click Save in the upper right corner to complete message creation. Also we can click Preview to preview the display effect of your message on a mobile phone or tablet.
Note: Do not hit the publish button yet. Just save it.
Step 14: In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. To that we need to find the message that you need to test, and click Test in the Operation column as it is shown below:
Step 15: Click Add test user and enter the AAID of the test device in the text box. Also run the app in order to find AAID of the test device in the logcat of the Android Studio.
Step 16: Finally we will publish the message. We will select publish in the operation column. It will look like this:
The Dish

Intermediate: How to integrate Huawei kits (IAP, Crash Service) into learning app (Flutter)

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

How to Integrate Location Kit in HarmonyOS Watches

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 Kit​1. 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 Introduction​I 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 Procedure​I'll now show you how to run the demo using source code, so that you can understand how it is implemented.
Preparations​1. 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 Steps​1. 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 Code​1. 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 Parameters​1. 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

Learn to integrate Login via Facebook using Huawei Auth Service (React Native)

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

Integrate Huawei's UserDetect to Prevent Fake and Malicious Users

Background​
Recently, I was asked to develop a pet store app that can filter out fake users when they register and sign in, to cut down on the number of fake accounts in operation. I was fortunate enough to come across the UserDetect function of HMS Core Safety Detect at the Huawei Developer Conference, so I decided to integrate this function into this app, which turned out to be very effective. Currently, this function is free of charge and is very successful in identifying fake users, helping prevent credential stuffing attacks, malicious posting, and bonus hunting from fake users.
Now, I will show you how I integrate this function.
Demo and Sample Code​
The HUAWEI Developers website provides both Java and Kotlin sample code for the UserDetect function and other four functions of Safety Detect. Click here to directly download the sample code. You can modify the name of the downloaded sample code package according to tips on the website, and then run the package.
Here is my sample code. Feel free to have a look.
Preparations​
Installing Android Studio​
To download and install Android Studio, visit the Android Studio official website.
Configuring App Information in AppGallery Connect​
Before developing your app, follow instructions here to configure app information in AppGallery Connect.
Configuring the Huawei Maven Repository Address​
The procedure for configuring the Maven repository address in Android Studio differs for Gradle plugin versions earlier than 7.0, Gradle plugin 7.0, and Gradle plugin 7.1 or later. Here I use version 7.1 or later as an example.
Note that the Maven repository address cannot be accessed from a browser and can only be configured in the IDE. If there are multiple Maven repositories, add the Maven repository address of Huawei as the last one.
1. Open the project-level build.gradle file in your Android Studio project.
{
"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"
}
2. If the agconnect-services.json file has been added to the app, go to buildscript > dependencies and add the AppGallery Connect plugin configuration and Android Gradle plugin configuration.
Code:
buildscript {
dependencies {
...
// Add the Android Gradle plugin configuration. You need to replace {version} with the actual Gradle plugin version, for example, 7.1.1.
classpath 'com.android.tools.build:gradle:{version}'
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
}
}
plugins {
...
}
3. Open the project-level settings.gradle file and configure the Maven repository address for the HMS Core SDK.
Code:
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
// Configure the Maven repository address for the SDK.
maven { url 'https://developer.huawei.com/repo/' }
}
}
dependencyResolutionManagement {
...
repositories {
google()
mavenCentral()
// Configure the Maven repository address for the SDK.
maven { url 'https://developer.huawei.com/repo/' }
}
}
Adding Build Dependencies​
1. Open the app-level build.gradle file of your project.
2. Add the AppGallery Connect plugin configuration in either of the following methods:
Method 1: Add the following configuration under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration:
id 'com.huawei.agconnect'
}
3. Add a build dependency in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:safetydetect:{version}'
}
Note that you need to replace {version} with the actual SDK version number, for example, 6.3.0.301.
Configuring Obfuscation Scripts​
If you are using AndResGuard, add its trustlist to the app-level build.gradle file of your project. You can click here to view the detailed code.
Code Development​
Creating a SafetyDetectClient Instance​
Code:
// Pass your own activity or context as the parameter.
SafetyDetectClient client = SafetyDetect.getClient(MainActivity.this);
Initializing UserDetect​
Before using UserDetect, you need to call the initUserDetect method to complete initialization. In my pet store app, I call the initialization method in the onResume method of the LoginAct.java class. The code is as follows:
Code:
@Override
protected void onResume() {
super.onResume();
// Initialize the UserDetect API.
SafetyDetect.getClient(this).initUserDetect();
}
Initiating a Request to Detect Fake Users​
In the pet store app, I set the request to detect fake users during user sign-in. You can also set the request to detect fake users in phases such as flash sales and lucky draw.
First, I call the callUserDetect method of SafetyDetectUtil in the onLogin method of LoginAct.java to initiate the request.
My service logic is as follows: Before my app verifies the user name and password, it initiates fake user detection, obtains the detection result through the callback method, and processes the result accordingly. If the detection result indicates that the user is a real one, the user can sign in to my app. Otherwise, the user is not allowed to sign in to my app.
Code:
private void onLogin() {
final String name = ...
final String password = ...
new Thread(new Runnable() {
@Override
public void run() {
// Call the encapsulated UserDetect API, pass the current activity or context, and add a callback.
SafetyDetectUtil.callUserDetect(LoginAct.this, new ICallBack<Boolean>() {
@Override
public void onSuccess(Boolean userVerified) {
// The fake user detection is successful.
if (userVerified){
// If the detection result indicates that the user is a real one, the user can continue the sign-in.
loginWithLocalUser(name, password);
} else {
// If the detection result indicates that the user is a fake one, the sign-in fails.
ToastUtil.getInstance().showShort(LoginAct.this, R.string.toast_userdetect_error);
}
}
});
}
}).start();
}
The callUserDetect method in SafetyDetectUtil.java encapsulates key processes for fake user detection, such as obtaining the app ID and response token, and sending the response token to the app server. The sample code is as follows:
Code:
public static void callUserDetect(final Activity activity, final ICallBack<? super Boolean> callBack) {
Log.i(TAG, "User detection start.");
// Read the app_id field from the agconnect-services.json file in the app directory.
String appid = AGConnectServicesConfig.fromContext(activity).getString("client/app_id");
// Call the UserDetect API and add a callback for subsequent asynchronous processing.
SafetyDetect.getClient(activity)
.userDetection(appid)
.addOnSuccessListener(new OnSuccessListener<UserDetectResponse>() {
@Override
public void onSuccess(UserDetectResponse userDetectResponse) {
// If the fake user detection is successful, call the getResponseToken method to obtain a response token.
String responseToken =userDetectResponse.getResponseToken();
// Send the response token to the app server.
boolean verifyResult = verifyUserRisks(activity, responseToken);
callBack.onSuccess(verifyResult);
Log.i(TAG, "User detection onSuccess.");
}
})
}
Now, the app can obtain the response token through the UserDetect API.
Obtaining the Detection Result​
Your app submits the obtained response token to your app server, and then your app server sends it to the Safety Detect server to obtain the detection result. You can obtain the user detection result using the verify API on the cloud.
The procedure is as follows:
1. Obtain an access token.
a. Sign in to AppGallery Connect and click My projects. Then, click your project (for example, HMSPetStoreApp) and view the client ID and client secret on the Project settings page displayed.
b. Use the client ID and client secret to request an access token from the Huawei authentication server. You can find out more details in the "Client Credentials" chapter on OAuth 2.0-based Authentication.
2. Call the Safety Detect server API to obtain the result.
The app will call the check result query API of the Safety Detect server based on the obtained response token and access token. You can visit the official website for details about how to call this API.
The app server can directly return the check result to the app, which will either be True, indicating a real user, or False, indicating a fake user. Your app can respond based on the check result.
Disabling UserDetect​
Remember to disable the service to release resources after using it. For example, I call the disabling API in the onPause method of the LoginAct.java class of my app to disable the API.
Code:
@Override
protected void onPause() {
super.onPause();
// Disable the UserDetect API.
SafetyDetect.getClient(this).shutdownUserDetect();
}
Conclusion​
And that's how it is integrated. Pretty convenient, right? Let's take a look at the demo I just made.
You can learn more about UserDetect by visiting Huawei official website.

Categories

Resources