AppsUP contest has been launched since June 30. Many developers meet the following issues in the process. If you also have the same issue which needs to be resolved, these questions in the list will be timely help. Any doubts or questions about Analytics Kit, this post can be a reference.
Q: When I integrate analysis kit, the compilation errors occurs in React Native Version 0.59.8
A: If you are migrating your app to HMS, suggest you to cross reference your original project and simply add the line to the buildscript/repositories and allprojects/repositories blocks.
The details you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248163576960163&fid=0101187876626530001
Q: Can we change the data storage for Advanced Analytics and How?
A: Till now there is no option to change the Data Storage Location, but you can reset it by deleting your existing app and recreating the app. Then you will see the option to set data storage location option during configuring the developer option. At the same time you must be careful about setting of Data Storage Location because once it set you can't change or modify it.
Q: Huawei analysis shows that the user data does not match the user data displayed on the background of Huawei analysis.
A: According to Huawei analysis, all users are virtual users.
If an application is uninstalled and then reinstalled on a mobile phone, the number of users is counted as two.
Therefore, the number of users calculated by Huawei analysis is greater than or equal to the actual number of users.
Q: If developers need to report some customized user property, which API can be use?
A: You should use "setUserProfile" method of this class: com.huawei.hms.analytics.HiAnalyticsInstance
Attributes will be reported to AGC Analytics and will be usable.
API description is as below:
{
"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"
}
link:
https://developer.huawei.com/consumer/en/doc/development/HMS-References/3021008#setUserProfile
Q: How to export data to an app server through the data export API provided by the Analytics Kit gateway?
A: Before calling Analytics Kit APIs, you need to obtain the token for authentication. This process involves three parameters, wherein: client_id is the app ID obtained during app creation, client_secret is the password for the app ID that can be queried on HUAWEI Developers, grant_type has a fixed value of client_credentials. In the following example, the getToken() method sends a POST request encapsulating the HTTP tool class to obtain the token and convert the obtained token into an object for subsequent authentication.
More details, you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201302699264940068&fid=0101187876626530001
Q: Integrated Analytics Kit, Why Does the Server Return Error Code 402 When Data Fails to Be Reported?
A: Developers have modified the agconnect-services.json configuration. As a result, the app fails to obtain the AGC token.
Q: Where Is Entry Menu of HUAWEI Analytics Kit?
A: HUAWEI Analytics Kit has been enhanced to provide the cross-platform analysis capabilities, allowing one-stop, unified analysis of Android and iOS users. It looks into the user-centric analysis and helps you understand user behavior on the Android and iOS platforms. For easier access, the entry menu on AppGallery Connect has been changed from Analyze > Advanced analysis (beta) to My projects > HUAWEI Analytics. You can view the overall analysis report or analysis report specific to a certain platform or app in your project. You can even compare user behaviors of different apps and platforms.
Q: Why reporting of custom events fails when I was conducting cross-platform data analysis using User-ID?
A: Event ID definition rule of HUAWEI Analytics Kit: An event ID cannot be left empty or contain spaces. It can consist of a maximum of 256 characters including digits, letters, and underscores (_) but cannot start with a digit. In addition, its value cannot be the same as the ID of an automatically collected event.
Therefore, you can change Purchase Test to Purchase_Test or any other value that complies with the preceding rule.
If you have multiple iOS and Android apps in a project, you can use the filter to view the overall analysis report or detailed report of an app. You can even link users' activity data from different devices by using User-ID to obtain cross-platform analysis data. For details about cross-platform analysis, see:
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/3021001
Q: I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
A: When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Q: What should I do if data reporting fails and the server returns error code 401?
A: Cause Analysis:
Possible causes are as follows:
HUAWEI Analytics Kit has not been enabled.
The obtained agconnect-services.json file is not the original file.
The debug mode has not been successfully enabled.
The Logcat log data on the device is not reported successfully.
Solution:
To correct the fault, perform the following steps:
Check whether HUAWEI Analytics Kit has been enabled and whether it has been turned on (default) in the API management.
Check whether the agconnect-services.json file is the original file without any modification.
Check whether the debug mode is enabled.
Check whether the log data is reported successfully. If the log contains resultCode: 200, the data is reported successfully. Possible causes are as follows:
Case 1: The tools:node parameter is set to "replace" (that is, tools:node="replace"). This causes the app configuration to conflict with AppGallery Connect SDK configurations, and therefore an exception occurs when the AppGallery Connect API is called to obtain the token.
Case 2: The configuration for excluding HUAWEI Analytics Kit from obfuscation is not added before you compile the APK. As a result, an exception occurs during the running of the APK.
Open the obfuscation script file of your project.
Add configurations to exclude HUAWEI Analytics Kit from obfuscation.
Set tools:node to "merge" (that is, tools:node="merge").
Manually write all information in the AndroidManifest.xml file of AppGallery Connect to the AndroidManifest.xml file of your app.
Code:
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agconnect.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
Related articles you can refer:
[AppsUP] Frequently Asked Questions About Huawei Account Kit
[AppsUP] Frequently Asked Questions About Huawei Map Kit
[AppsUP] Frequently Asked Questions About Huawei Push Kit
More doubts or questions about Analytics Kit, leave your comment below or ask your questions in HUAWEI Developer Forum.
Related
More articles like this, you can visit HUAWEI Developer Forum
HUAWEI Analytics Kit 5.0 version has been updated, and it supports iOS SDK now, enabling one-stop, unified analysis of cross-platform Android and iOS users. It looks into user-centric analysis and helps you understand user behavior on the Android and iOS platforms. Today I want to share with you how to add Analytics Kit to your iOS App. The version I integrated is 5.0.0.300.
The general steps we will walk through include:
Configuring App Information in AppGallery Connect
Integrating the HMS Core SDK
Accessing HUAWEI Analytics Kit
Configuring App Information in AppGallery Connect
Follow the steps below to configure App Information in AppGallery Connect for your iOS application. If you have both an Android and an iOS version of your app, you can set them within the same project, this will allow you to finish the data analysis conveniently.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Getting Started:
1. Have your Bundle ID ready for your iOS app (ask your developers for this).
2. Go to AppGallery Connect and create a new project.
Once you’ve created a new project, you’ll see a page, and the side navigation bar shows the AGC's various function menus.
3. Click Add app, and create an iOS application.
Here the App package ID is the Bundle ID.
Click OK, and then you will get the configuration file agconnect-services.plist.
Click Manage APIs, and here we’ve already had the Analytics API enabled.
Back to the side navigation bar, and go to the HUAWEI Analytics tab, you will see all kinds of functions, including User analysis, Behavior analysis, etc. Select any menu to Enable Analytics service.
On the Project access settings page, set the data storage location, time zone, currency, user data storage time, and calendar week, and click Finish.
Integrating the HMS Core SDK (in Cocoapods Mode)
I prefer the Cocoapods Mode. You can also integrate the HMS Core SDK into the Xcode Project Manually.
1. Add the AppGallery Connect configuration file of the app to your XCode project.
a. Click Download agconnect-services.plist to obtain your iOS config file (agconnect-services.plist).
b. Move your agconnect-services.plist file into the root of your Xcode project.
2. Edit the Podfile file
a. Create a Podfile if you don't already have one:
$ cd your-project-directory
$ pod init
b. To your Podfile, add the pods that you want to use in your app: Add pod 'HiAnalytics', that is, the dependency for pod.
Example Podfile file:
Code:
# Uncomment the next line to define a global platform for your project
# platform :iOS, '9.0'
target 'HiAnalyticsSwiftDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for HiAnalyticsSwiftDemo
pod 'HiAnalytics'
target 'HiAnalyticsSwiftDemoUITests' do
# Pods for testing
end
end
c. Install the pods, then open your .xcworkspace file to see the project in Xcode:
$ pod install
$ open your-project.xcworkspace
Accessing HUAWEI Analytics Kit
1. Initialize Analytics SDK in your app
The final step is to add initialization code to your application. Initialize AppDelegate through the config interface.
Objective C sample code: Perform initialization in AppDelegate.m.
Code:
#import "AppDelegate.h"
#import <HiAnalytics/HiAnalytics.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
...
- (BOOL)Application:(UIApplication *)Application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after Application launch.
[HiAnalytics config];//Initialization
return YES;
}
...
@end
Swift code example: Perform initialization in AppDelegate.swift.
Code:
import UIKit
import HiAnalytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func Application(_ Application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after Application launch.
HiAnalytics.config();//Initialization
return true
}
...
}
2. Record defined events using the onEvent API.
For definitions of the events, please refer to Event Description.
3. Call APIs of HUAWEI Analytics Kit to implement the corresponding functions. For details, please refer to API Reference.
During the development, you can use DebugView to view the event records in real time, observe the results, and adjust the event tracing scheme.
Enabling/Disabling the Debug Mode
1.To enable the debug mode:
Go to Product > Scheme > Edit Scheme from the Xcode menu. On the Arguments page, click + to add the -HADebugEnabled parameter. After the parameter is added, click Close to save the setting.
Code:
1. –HADebugEnabled
2.To disable the debug mode
Code:
1. -HADebugDisabled
After the data is successfully reported, you can go to HUAWEI App Debugging to view the data, as shown in the following figure.
Q&A:
1. I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Face problems during development? Take it easy. Go to Stack Overflow and raise your questions. Huawei experts will get back to you as soon as possible.
https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest
Hi everyone,
In this article, we will convert a GMS project which has Location, Map and Analytics APIs to GMS+HMS project step by step. In order to do that, I prepared an initial project which has those APIs for you to download.
You can find and download the GitHub link of the initial project in this link. This project contains the main features of the Google Location, Map, Analytics APIs. We will install HMS toolkit plugin to Android Studio, configure the project with App Gallery Connect, and finally convert it step by step.
Installing the HMS toolkit plugin
We start by installing the HMS toolkit plugin in Android Studio. For this in the Android Studio window, you should open settings by navigating File -> Settings. In the marketplace, search for HMS toolkit and install the plugin.
{
"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"
}
After installing the HMS toolkit, you will be prompt that you need to restart Android Studio. Follow the instruction and restart the IDE. After restarting the IDE, you will see the HMS section in the toolbar of Andriod Studio.
Running the initial project
As it is mentioned before, the initial project has Google Location, Map and Analytics APIs. When you run the project in a GMS device, it should look like this;
As you can see in the figure, there are three activities which are for Map, Location and Analytics APIs. This initial project only works on devices with Google Mobile Services. Next step is configuring our project with Huawei Mobile Services.
Creating a New Project in AppGallery Connect
The first thing we are going to do is creating a project through the AppGallery Connect platform. Go to this link and create a developer account. Then go to the console by clicking the console button at the left top corner in the web page. Click on , then click on “My Apps”. Afterwards, you will need to create a new app by clicking the “New App” button at the left top corner. Fill the necessary parts accordingly.
After creating the app, we are going to configure our project in the AppGallery Connect. In order to do that, at the navigation window near the AppGallery Connect logo, click “My projects” section.
The project page will ask us to fill the package name section. This will also help our toolkit to automatically match between the Android Studio and AppGallery Connect.
After configuring the package name, in the “Project Settings” page, you should set your Data Storage location.
Also, we are gonna activate the APIs that we are going to convert from Google Mobile Services by opening the “Manage APIs” page. In our case, we need to activate Location Kit, Analytics Kit and Map Kit. In order to activate the Analytics kit, you should enable Analytics Kit at the “Project Overview”, in the HUAWEI Analytics section which is shown in the navigation bar on the left.
For creating a new app on AppGallery Connect, please refer to the official documentation.
Configuring the Project Using HMS toolkit- Configuration Wizard
Now we can continue to configure our project with HMS toolkit in Android Studio. When you click the HMS section, you will see the window which you can use the features of the HMS toolkit. In this article, we will use Configuration Wizard and Convertor.
We are going to use Configuration Wizard in order to configure our project, connect the project with App Gallery Connect, create a keystore.jks file, download the related agconnect-services.json file and configure the related APIs for the project.
In order to configure our project, we will need to set the fingerprint of our project. We are going to choose “Use your certificate” option and create a new fingerprint for our project as seen in the figure below.
After creating fingerprint and starting the configuration process, the configuration wizard will start analyzing and configuring our project. It will match the Android Studio project with the AppGallery project, download necessary settings, service files and configure the fingerprint in the project.
Converting the project with HMS toolkit convertor
We configured our project successfully. Next, we are going to convert our project. We will start the conversion process by selecting Convertor -> New Conversion.
Follow the conversion procedure as shown below. Select a backup directory to prevent any unexpected errors. By doing this, you will be able to restore your project to the version before the conversion
In this part, you will see the analysis of automatic conversion rate. In our case, we have a %100 auto conversion rate and we will not have to convert anything manually. Since we are going to convert our project to GMS+HMS project, we are going to select the conversion policy as “Add HMS API(HMS API First)” then we will click “Analyze” button.
After the analysis is finished, we will have an analysis report as seen in the figure below. As we can see, there are auto conversion entries as well as manual conversion. In order to solve those manual conversion entries, we are going to click “Details” in the corresponding entry and follow the procedures. In order to start the automatic conversion, we are going to select all the automatic conversion entries and click the convert button.
Auto: This item will be automatically converted.
Dummy: HMS does not support this method. The XMS Adapter encapsulates only the GMS method. You need to confirm whether to retain or delete this method in or from HMS. After the confirmation, you can start an automatic conversion.
Manual: This item requires manual conversion.
Since we selected G+H conversion, convertor added the XMS Adapter to the project, an adaption-layer code module, based on the original code for calling third-party APIs. The adapter code can call GMS APIs or HMS APIs based on the scheduling policy. The scheduling policy is determined by us. In this project, we selected the policy of “HMS APIs first”.
The XMS Adapter automatically generated by the tool schedules GMS APIs and HMS APIs and separates or decouples service code from adapter code. You only need to pay attention to services and do not need to spend much time on the differences between GMS APIs and HMS APIs.
For details about the principle, please refer to Add HMS API Policy.
After the conversion, we are synchronizing the build.gradle files and check the project whether we have any errors. Because we are developing this project in Kotlin, we encountered some getter setter errors.
In order to fix those errors, we will change the getter setter functions as we are doing in Java.
Testing the converted project with both GMS and HMS devices
After we fix all the errors in the project, now we are ready to run the project both in the GMS device and the HMS device. As it is seen in the figures below, the application is working on the HMS only device. If we run it on the GMS only devices, it will also work without any problem.
If we also check the App Debugging section of HUAWEI Analytics in the AppGallery Connect Platform, it will be seen that the Analytics kit is also working exactly how it should.
Conclusion
Migrating a complex project from GMS to HMS is very easy with HMS toolkit conversion. Thanks to XMSAdapter architecture that HMS toolkit provides, the application chooses GMS APIs or HMS APIs according to the availability of the services.
Please also refer to the official documentation of HMS toolkit: link
You can also find and download the fully converted version of the project here.
Any questions about the process, you can ask a question in https://forums.developer.huawei.com/forumPortal/en/home
Do we have something like Firebase UI in this plugin ?
Freemind R said:
Migrating a complex project from GMS to HMS is very easy with HMS toolkit conversion.
Click to expand...
Click to collapse
Yeah right. I just tried the converter tool on a complex project and in the generated code I see tons of
Code:
XMS does not provide this api
and
Code:
throw new java.lang.RuntimeException("Not Supported");
There are more that 100 such occurrences in the code. Also converter skips lot of things in the code base which need to be converted manually.
Also it doesn't detect some of google apis at all (places sdk).
Also it generates tons of gradle modules and flavors for no reason, so building a project takes forever.
So basically this converter tool is a garbage. Don't waste your time.
Introduction
In this article, we will cover how to verify Phone Number and Anonymous Account Login using Huawei Auth Service in Unity Project using Official Plugin (Huawei HMS Core App Services). AppGallery Connect provides a cloud-based Auth Service and SDKs to help you quickly build a secure and reliable user authentication system for your apps to verify user identity.
The AppGallery Connect Auth service supports multiple authentication methods and is seamlessly integrated with other server less services to secure user data based on simple rules that you have defined.
Key FunctionsUsing the AppGallery Auth Service SDK, you can integrate one or more of the following authentication methods into your app for achieving easy and efficient user registration and sign-in.
Self-owned account: Your self-owned account is used to support the access of your existing authentication system, so that your existing users can access other server less services in a secure manner.
Anonymous account: Anonymous accounts can be used to access your apps as visitors. The Auth service can assign user IDs to your app visitors, so that they can access other server less services in a secure manner. A visitor can be registered as a formal user and retain the original user ID to ensure service continuity.
Third-party accounts: AppGallery Connect allows user identity to be verified by third-party authentication services. The AppGallery Auth Service SDK supports the following accounts for user identity verification:
1. HUAWEI account
2. HUAWEI Game Service account
3. Phone number
4. Email account
5. WeChat account
6. Weibo account
Development Overview
You need to install Unity software and I assume that you have prior knowledge about the unity and C#.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK installation package.
Unity software installed.
Visual Studio/Code installed.
HMS Core (APK) 4.X or later.
Follows the steps.
1. Create Unity Project.
Open Unity Hub.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows
{
"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. Click Asset Store, search Huawei HMS Core App Services and click Import, as follows.
3. Once import is successful, verify directory in Assets > Huawei HMS Core App Services path, as follows.
4. Choose Edit > Project Settings > Player and edit the required options in Publishing Settings, as follows.
5. Generate a SHA-256 certificate fingerprint.
To generating SHA-256 certificate fingerprint use below command
keytool -list -v -keystore D:\Unity\projects_unity\file_name.keystore -alias alias_name
6. Download agconnect-services.json and copy and paste to Assets > Plugins > Android, as follows.
7. Choose Project Settings > Player and update package name.
8. Open LauncherTemplate.gradle and add below line.
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.301'
implementation 'com.huawei.hms:base:5.2.0.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
9. Open AndroidManifest file and add below permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
10. Open "baseProjectTemplate.gradle" and add lines, as follows.
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
maven {url 'https://developer.huawei.com/repo/'}
11. Open "mainTemplate.gradle" and add lines like shown below.
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.301'
implementation 'com.huawei.hms:base:5.2.0.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
12. Create MainActivity.java class inside Plugin > Android folder.
13. Follow the steps, as shown in image:
a. Assign Ads script to Canvas.
b. Select Button and add onclick event
c. Assign all button to button handler as per your requirements.
14. Onclick Button Handler you find your script HMSAuthService (As per your script name) and attach method as per below screen shot.
15. To build apk and run in device, choose File > Build Settings > Build for apk or Build and Run for run on connected device.
Result
1. Click on Anonymous Login, send OTP and Verify button you can see below results.
2. Find the details in AppGallery Connect, as follows.
Tips and Tricks
Always use the latest version of the library.
Add agconnect-services.json file without fail.
Add SHA-256 fingerprint without fail.
Make sure dependencies added in build files.
Make sure that you enabled the auth service in AG-Console.
Make sure that you enabled the Authentication mode in Auth Service.
Conclusion
In this article, we have learnt integration of Huawei Auth Service-AGC anonymous account login and mobile number verification through OTP in Unity Game development. Auth Service provides secure and reliable user authentication system to your application.
Thanks for reading the article, please do like and comment your queries or suggestions.
References
Unity Auth Service Manual
Auth Service
Checkout in forum
{
"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, we can learn how to integrate Huawei Crash service of AppGallery Connect in Attendance Tracker application.
So, I will provide the series of articles on this Attendance Tracker App, in upcoming articles I will integrate other Huawei Kits.
If you are new to this application, follow my previous articles
Beginner: Integration of Huawei Account Kit of Obtaining Icon Resources feature in Attendance Tracker Android app (Kotlin) - Part 1
Beginner: Find Log in via SMS and Forgot password? Features using Huawei Account Kit, and Ads Kit in Attendance Tracker Android app (Kotlin) – Part 2
Beginner: Find the CRUD operations in Room Database in Attendance Tracker Android app (Kotlin) – Part 3
What is Crash service?
The AppGallery Connect Crash service provides a powerful 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 need to write any code.
Huawei Crash is a realtime crash reporting tool that helps in tracking, prioritizing, and fix stability issues that compromise the quality of your app.
To ensure stable running of your app and prevent user experience deterioration caused by crashes, you are advised to monitor the running status of your app on each device, which is the key. The Crash service provides real-time reports, revealing any crash of your app on any device. In addition, the Crash service can intelligently aggregate crashes, providing context data when a crash occurs, such as environment information and stack, for you to prioritize the crash easily for rapid resolution.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.0.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 and above installed.
4. Minimum API Level 24 is required.
5. Required EMUI 9.0.0 and later version devices.
How to 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. On right-upper corner of android project click Gradle, choose Project Name > Tasks > android, and then click signingReport, as follows.
Note: Project Name depends on the user created name.
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 button, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and enable HUAWEI Analytics.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Analytics
implementation 'com.huawei.hms:hianalytics:6.4.0.300'
// Huawei Crash Service
implementation 'com.huawei.agconnect:agconnect-crash:1.6.0.300'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Configuration in AppGallery Connect
Find the Crash using AppGallery connect dashboard.
Choose My Projects > Quality > Crash, and click Enable now.
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
1. Initialize an AGConnectCrash before other methods and Enable crash.
Java:
AGConnectCrash.getInstance().enableCrashCollection(true)
2. Test the below method in your code.
Java:
AGConnectCrash.getInstance().testIt([email protected])
3. Customizing User IDs: Analyzing crashes by a user to resolve crashes using User ID. The user can be uniquely identified after a crash occurs.
Java:
AGConnectCrash.getInstance().setUserId("123456789")
4. Recording Custom Logs: we can record custom logs, Recorded logs will be reported together with the crash data.
Java:
AGConnectCrash.getInstance().log("catch exception")
5. Adding a Custom key-value pair: we can add a custom key-value pair to record the status. The recorded status will be reported together with the crash data.
Java:
AGConnectCrash.getInstance().setCustomKey("keyInt", 1)
In the Home.kt activity to find the business logic for crash service.
Java:
class Home : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
img_profile.setOnClickListener {
val intent = Intent([email protected], EmployeesList::class.java)
startActivity(intent)
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
// Test
AGConnectCrash.getInstance().testIt([email protected])
}
AGConnectCrash.getInstance().enableCrashCollection(true)
// Record Custom Status
AGConnectCrash.getInstance().setCustomKey("keyInt", 1)
// Set the user ID
AGConnectCrash.getInstance().setUserId("123456789")
try {
throw NullPointerException()
} catch (ex: NullPointerException) {
AGConnectCrash.getInstance().log("catch exception")
// Record non-fatal exception
AGConnectCrash.getInstance().recordException(ex)
}
}
}
Result
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
3. Make sure you have added the agconnect-services.json file to app folder.
4. Make sure you have added SHA-256 fingerprint without fail.
5. Make sure all the dependencies are added properly.
Conclusion
In this article, we have learnt the integrate of Huawei Crash service of AppGallery Connect in Attendance Tracker application. Crash service provides a powerful 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 need to write any code.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Crash Service – Documentation
Crash Service – Training Video
Account Kit provides simple, secure, and quick sign-in and authorization functions. Rather than having users enter accounts and passwords and wait for authentication, you can let your users simply tap Sign in with HUAWEI ID to quickly and securely sign in to an app with their HUAWEI IDs.
And this is the very reason why I integrated this kit into my app. While doing so, I encountered and collated some common issues related to this kit, as well as their solutions, which are all listed below. I hope you find this helpful.
1. What is redirect_url and how to configure it?redirect_url, or redirection URL, is not the real URL of a specific webpage. Its value is a character string starting with https://. Although it can be customized to whatever you want, you are advised to assign a meaningful value to this parameter according to your service's features.
According to OAuth 2.0, in a web app, redirect_url works in the following scenario: After obtaining user authorization from the OAuth server, the web app will jump to the redirection URL. The web app needs to obtain the authorization code through the URL. To obtain an access token, pass the URL as a parameter to the request that will be sent to the OAuth server. Then, the server will check whether the URL matches the authorization code. If so, the server will return an access token, but if it doesn't, it will return an error code instead.
Check out the instructions in Account Kit's documentation to learn how to set a redirection URL.
2. What's the difference between OpenID and UnionID?An OpenID uniquely identifies a user in an app, but it differs for the same user in different apps.
A UnionID uniquely identifies a user across all apps created under the same developer account.
Specifically speaking, after a user uses their HUAWEI ID to sign in to your apps that have integrated Account Kit, the apps will obtain the OpenIDs and UnionIDs of that user. The OpenIDs are different, but the UnionIDs are the same. In other words, if you adopt the OpenID to identify users of your apps, a single user will be identified as different users across your apps. However, the UnionID for a single user does not change. Therefore, if you want to uniquely identify a user across your apps, the UnionID is advised. Note that if you transfer one of your apps from one developer account to another, the UnionID will also change.
3. How do I know whether an account has been used to sign in to an app?To know this, you can call the style='mso-bidi-font-weight:normal'>silentSignIn API. If the value of the returned style='mso-bidi-font-weight:normal'>authAccount object in style='mso-bidi-font-weight:normal'>onSuccess is not null, this indicates that the account has been used to sign in to an app.
Code:
Task<AuthAccount> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
if(null != authAccount) {
showLog("success ");
}
}
});
4. What to do when error invalid session is reported after the user.getTokenInfo API is called?1. Check whether all input parameters are valid.
2. Confirm that the access_token parameter in the request body has been converted through URL encoding before it is added to the request. Otherwise, if the parameter contains special characters, invalid session will be reported during parameter parsing.
{
"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"
}
Click here to know more details about this API.
5. Is redirect_uri a mandatory parameter in the API for obtaining an access token?Whether this parameter is mandatory depends on the usage scenarios of the API. Specifically speaking:
The parameter is mandatory, when the API is called to obtain the access token, refresh token, and ID token through the authorization code that has been obtained.
The parameter is not mandatory when a refresh token is used to obtain a new access token.
Check out the official instructions for this API to learn more.
6. How long is the validity of an authorization code, an access token, and a refresh token?Authorization code: valid for 5 minutes. This code can be used only once.
Access token: valid for 1 hour.
Refresh token: valid for 180 days.
7. Common result codes and their solutions907135700This code indicates a failure to call the gateway to query scopes of the app.
To solve it, try the following solutions:
1. Check whether the device can connect to the Internet as normal. If not, this could be because the network connection is unavailable and the network connection does not allow for accessing the site for downloading scopes, due to reasons such as firewall restriction.
2. Check whether the app has been created in AppGallery Connect.
3. Check whether the system time of the device is set to the current time. If not, the device SSL certificate will expire, which will prevent the scopes from being downloaded.
907135701This code indicates that scopes are not configured on OpenGW, which may be due to the insufficient application of services for the app and inconsistent environment settings.
To solve this error, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Check whether the app ID in agconnect-services.json is the same as the app ID in AppGallery Connect.
3. Check whether agconnect-services.json is placed under the app directory, as shown in the following figure.
4. Check whether the environments set for your app and HMS Core (APK) are the same, for example, whether they are all the live-network environment or testing environment.
907135702This code indicates that no certificate fingerprint is configured on OpenGW. To solve this, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Verify that the SHA-256 certificate fingerprint has been configured in AppGallery Connect. Click here to learn how.
6003This code indicates certificate fingerprint verification failed.
Verify that the certificate fingerprint in your app's APK file is consistent with that configured in AppGallery Connect, by following the steps below:
1. Open the APK file of your app, extract the META-INF directory from the file, obtain the CERT.RSA file in the directory, and run the keytool -printcert -file META-INF/CERT.RSA command to get the signing certificate information.
2. Sign in to AppGallery Connect, click My projects, and select the project you want to check. On the displayed page, select the app, go to Project settings > General information, and check whether the value in SHA-256 certificate fingerprint is the same as that in the previous step.
Click here to learn more about certificate fingerprint configuration.
ReferencesHMS Core Account Kit Overview
HMS Core Account Kit Development Guide