Pygmy Collection Application Part 3 (Crash service) - Huawei Developers

Introduction
In my last article, I have explained how to integrate account kit finance application. Have a look into Pygmy collection application Part 1 (Account kit). And Integration of Huawei Ads kit have look into Intermediate: Pygmy Collection Application Part 2 (Ads Kit)
What is Huawei Crash service?
In this article, we will learn how to integrate Crash services of AppGallery in Pygmy collection finance application.
Huawei Crash is a realtime crash reporting tool that helps in tracking, prioritizing, and fix stability issues that compromise the quality of your app. Crashlytics also helps in troubleshooting and saves the debugging.
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.
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.
Why do we need the crash service?
Although apps have gone through rounds the tests before release considering the large user base diverse device models and complex network environment. It’s inevitable for apps to crash occasionally. Crashes compromise user experience, users may even uninstall app due to crashes and your app is not going to get good reviews.
You can’t get sufficient crash information from reviews to locate crashes, therefore you can’t resolve them shortly. This will severely harm your business. That’s why we need to use the crash services in our apps to be more efficient.
How to integrate Crash Service
1. Configure the application on the AGC.
2. Client application development process.
1. Configure application on the AGC
Follow the steps
Step 1: We need to register as a developer account in AppGallery Connect. If you are already a developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on the current location.
Step 4: Generating a Signing Certificate Fingerprint.
Step 5: Configuring the Signing Certificate Fingerprint.
Step 6: Download your agconnect-services.json file, paste it into the app root directory.
Step 7: Enable Crash services.
{
"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"
}
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-crash:1.6.0.300'
// It is recommended that you integrate the APM SDK to further locate whether an app crash is caused by an app event or behavior such as ANR, launch, and network request.
Code:
implementation 'com.huawei.agconnect:agconnect-apms:x.x.x.xxx'
implementation 'com.huawei.hms:hianalytics:5.0.5.300'
Root level gradle dependencies.
Code:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add permission in AndroidManifest.xml
XML:
<application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
...
</application>
Step 4: Initialize Crash Service activity or application class
Step 5: Build Application
Enable Crash Service
Java:
AGConnectCrash.getInstance().enableCrashCollection(true);
Test Crash service.
Java:
AGConnectCrash.getInstance().testIt(context);
Set User Id
Java:
AGConnectCrash.getInstance().setUserId("12345");
Set Log without log level
Java:
AGConnectCrash.getInstance().log("set info log.");
Set Log with Log Level
Java:
AGConnectCrash.getInstance().log(Log.WARN, "set warn log.");
Set custom Key pair value.
Java:
AGConnectCrash.getInstance().setCustomKey("mobileNumber", "Phone number is empty");
// Add a key-value pair of the string type.
AGConnectCrash.getInstance().setCustomKey("UserName", "Basavaraj Navi");
// Add a key-value pair of the boolean type.
AGConnectCrash.getInstance().setCustomKey("isFirstTimeUser", false);
// Add a key-value pair of the double type.
AGConnectCrash.getInstance().setCustomKey("doubleKey", 1.1);
// Add a key-value pair of the float type.
AGConnectCrash.getInstance().setCustomKey("floatKey", 1.1f);
// Add a key-value pair of the integer type.
AGConnectCrash.getInstance().setCustomKey("intKey", 0);
// Add a key-value pair of the long type.
AGConnectCrash.getInstance().setCustomKey("longKey", 11L);
Record Exception
Java:
SimpleDateFormat format = new SimpleDateFormat(PygmyConstants.DOB_FORMAT);
try {
Date date = format.parse(dob);
customerEntity.setDateOfBirth(date);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
AGConnectCrash.getInstance().recordException(e);
}
Result
Tips and Tricks
Make sure you added agconnect-service.json file.
Add internet permission in AndroidManifest.xml.
You can also download the crash reports.
Conclusion
In this article, we have learnt what the Crash service is. And how to integrate the crash service. How to record log with log level and without log level. And also we have learn how to record exception.
Reference
Huawei Crash Service

Thanks for sharing!!!

Related

QUIZ MANIA GAME Featuring Huawei In App Purchase Kit & Ads Kit

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"
}
Back in the 90’s, it was a revolutionary to have your own website and putting an advertisement in the website was the only source of revenue. But today as space matures, it’s essential for brands to have a clear strategy to monetize their mobile presence. Some companies charge their users before downloading their apps. Others depend on in-app advertising as their sole revenue stream. But, for a lot of brands, their mobile monetization strategy relies entirely (or some part) on In App Purchase. To summarise, when a customer spends money within a mobile app, that’s an in-app purchase.
To make easier for users to make payments and developers to focus solely on app innovation, Huawei provided us with an extraordinary kit i.e. HMS Core In App Purchase (IAP) Kit.
HMS In App Purchase helps developers in variety of situation to earn revenue such as paying for access to a dating app’s special features, subscribing to a streaming music app’s premium tier, buying more gold bars in games etc.
DEMO
Check out the demo created by me to make you understand, How HMS Core In App Purchase works.
Today, in this article we are going to see how to integrate HMS In App Purchase in a simple yet complex Quiz Game app. To be honest everything can’t be covered in a single article. So, I have prepared a sample project and will provided the code on Github soon. I also tried making it simple as much as possible so that every beginner can understand it.
Settings Needed
1) First we need to create an app or project in the Huawei app gallery connect.
2) Provide the SHA Key and App Package name of the android project in App Information Section.
3) Provide storage location in convention section under project setting.
4) Enable In-App Purchase setting in Manage APIs section.
5) 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.
6) 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/' }
7) 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'
8) Copy and paste the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
9) Copy and paste below library in the app build.gradle file dependencies section.implementation 'com.huawei.hms:iap:4.0.2.300'
10) Put the below permission in AndroidManifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
11) Now Sync the gradle.
Essential Requirement
Become a Merchant
We need to be a merchant in order to use HMS IAP Kit. Also after making your account as merchant, it will take 1 or 2 business days for verification.
Steps:
a) Login to Huawei Developer website.
b) Go to console.
c) Under Settings you will find Merchant Service as shown below:
d) Provide our bank details information here as shown below:
e) Provide our tax related information here as shown below:
f) Finally click submit to save the record for verification.
Need Public Key
We need a public key which is used for subsequent payment signature verification and a parameter for configuring the subscription notification URL.
b) After the configuration is successful, we will be able to see a public key. This public key we will use later.
Steps:
a) On the Develop tab page, go to Earning > In-App Purchases from the navigation tree on the left and click Settings. If this is the first time we configure the IAP service, a dialog box is displayed for you to sign the agreement.
Need Sandbox Account
We need sandbox account in order to test HMS IAP. During app development and testing, we can test product payments with a test account in the sandbox environment. During the testing period, when a purchase is initiated by the test account, the Huawei IAP server will identify the test account and directly process a successful payment, without real payments made.
Steps:
a) Go to AGC and select users and permissions.
b) Select Test account as shown below:
c) Click Add button to add test account as shown below:
d) After this a testing account is added. Make sure to add account which is used in Huawei devices to login.
This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201255229704010231&fid=0101187876626530001
This app is a great example for how Huawei Ads Kit can be used to monetize your app.

Coding-free Integration of AppGallery Connect APM on Android Platform

When an app is used, such problems may occur: slow app launch, Application Not Responding (ANR), app crash, and network loading failure. These are the major issues that affect user experience.
To meet increasing demands of diagnosing performance problems, more and more app performance monitoring services have emerged in the market. HUAWEI AppGallery Connect provides full-process quality services in app development, testing, release, and analysis. you can also download the codelab to try it first.
1. HUAWEI AppGallery Connect APM
App Performance Management (APM) is one of the quality services provided by AppGallery Connect. This service can monitor app performance at the minute level, and is totally free of charge. It does its job by:
Collecting data about app launches, app screen rendering, network requests, and foreground/background activities automatically.
Monitoring ANR problems and recording relevant device information and log information when they occur.
Providing app performance data analysis reports for app optimizations.
Providing app performance data analysis reports for app optimizations.
Supporting custom traces to monitor app performance data in specific scenarios.
AppGallery Connect APM has the following edges over other app performance monitoring platforms:
Easy integration: You can integrate APM for app performance analysis without any coding.
Real-time monitoring: It takes only 15 minutes to generate a report based on collected performance data.
Comprehensive metrics: APM illustrates an app's performance in a myriad of dimensions such as app launches, ANR, screen rendering, and network requests, and also supports custom traces, indicators, and dimensions to provide a tailored report for your specific needs.
2. Integrating AppGallery Connect APM
You can easily complete the integration of the service by following instructions in the documentation provided by Huawei. You only need to add the required plug-in and SDK configurations to your code without any coding. There are just a few simple steps:
i. Create an app in AppGallery Connect and enable APM.
ii. Download and add the JSON file.
iii. Integrate the APM plug-in and the APM SDK.
iv. Configure the obfuscation file.
Then, you can package and run your app, and view its performance data later in AppGallery Connect.
2.1 Creating an App in AppGallery Connect and Enabling APM
Access AppGallery Connect, create an app, and enable APM. Ensure that your app package name is the same as that configured in the APK file. If you need to enable APM for an existing app, make sure that the app package name in the APK file is the same as that configured in AppGallery Connect when the app is created.
Then select an app under My projects, go to Quality > APM, and click Enable.
{
"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.2 Downloading and Adding the JSON File
Create an Android project in Android Studio. The package name must be the same as that in AppGallery Connect.
In AppGallery Connect, select an app under My projects, go to Project settings > App information, download agconnect-services.json, and place the file in the app directory of your Android project.
2.3 Integrating the APM Plug-in and the APM SDK
To configure the SDK address, open your Android project, and configure the following content in the project-level build.gradle file.
Code:
buildscript {
repositories {
// Configure the following address:
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
// Configure the following address:
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath 'com.huawei.agconnect:agconnect-apms-plugin:1.3.1.300'
}
}
allprojects {
repositories {
// Configure the following address:
maven {url 'https://developer.huawei.com/repo/'}
}
}
Open the app-level build.gradle file, and configure the following content.
Code:
// Configure the following address:
apply plugin: 'com.huawei.agconnect'
apply plugin: 'com.huawei.agconnect.apms'
dependencies {
// Configure the following address:
implementation 'com.huawei.agconnect:agconnect-apms:1.3.1.300'
}
2.4 Configuring the Obfuscation File
Find the app-level proguard-rules.pro file (confusion configuration file), and add the following items:
Code:
-keep class com.huawei.agconnect.**{*;}
-dontwarn com.huawei.agconnect.**
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
-keepattributes Exceptions, Signature, InnerClasses, LineNumberTable
For how to find the file, see the following figure.
2.5 Packaging the App for Testing
After integration, click Sync in the upper right corner of your project in Android Studio to package and run your app on an Android device. Then, you can view the data in AppGallery Connect.
For more data, you can install and run the app on multiple devices.
3. Viewing Performance Data and ANR Data
Once you have run your app on a device, go back to AppGallery Connect. Find the app under My projects, go to Quality > APM, and view its performance data during testing.
As mentioned before, the performance data that you can view is diverse. The following is a sample report for your reference:
3.1 Overview
3.2 App Analysis
3.3 ANR Analysis
3.4 Network Analysis
4. Summary
In only 4 steps, you can integrate the HUAWEI AppGallery Connect APM SDK without coding, to implement comprehensive app performance monitoring.
The APM analysis report provides detailed device, log, and performance information recorded when an issue occurs. This real-time report drives app operations based on data and provides abundant information for app optimizations. App R&D and operations personnel no longer need to spend much time on locating and reproducing performance problems.
Codelab of APM in Android: https://developer.huawei.com/consumer/en/codelab/AppGalleryConnectAPM/index.html#0
Is it required to have agconnect.json file as mentioned in the post ?
Good
Very clear
sanghati said:
Is it required to have agconnect.json file as mentioned in the post ?
Click to expand...
Click to collapse
yes,you need to add your agconnect-services.json in your android studio project as following.
Thanks for sharing
This service can monitor the ANR of the App, which is very useful for me.

Coding-free Integration of AppGallery Connect APM on Android Platform

When an app is used, such problems may occur: slow app launch, Application Not Responding (ANR), app crash, and network loading failure. These are the major issues that affect user experience.
To meet increasing demands of diagnosing performance problems, more and more app performance monitoring services have emerged in the market. HUAWEI AppGallery Connect provides full-process quality services in app development, testing, release, and analysis.
1. HUAWEI AppGallery Connect APM
App Performance Management (APM) is one of the quality services provided by AppGallery Connect. This service can monitor app performance at the minute level, and is totally free of charge. It does its job by:
Collecting data about app launches, app screen rendering, network requests, and foreground/background activities automatically.
Monitoring ANR problems and recording relevant device information and log information when they occur.
Providing app performance data analysis reports for app optimizations.
Supporting custom traces to monitor app performance data in specific scenarios.
AppGallery Connect APM has the following edges over other app performance monitoring platforms:
Easy integration: You can integrate APM for app performance analysis without any coding.
Real-time monitoring: It takes only 15 minutes to generate a report based on collected performance data.
Comprehensive metrics: APM illustrates an app's performance in a myriad of dimensions such as app launches, ANR, screen rendering, and network requests, and also supports custom traces, indicators, and dimensions to provide a tailored report for your specific needs.
2. Integrating AppGallery Connect APM
You can easily complete the integration of the service by following instructions in the documentation provided by Huawei. You only need to add the required plug-in and SDK configurations to your code without any coding. There are just a few simple steps:
Create an app in AppGallery Connect and enable APM.
Download and add the JSON file.
Integrate the APM plug-in and the APM SDK.
Configure the obfuscation file.
Then, you can package and run your app, and view its performance data later in AppGallery Connect.
2.1 Creating an App in AppGallery Connect and Enabling APM
Access AppGallery Connect, create an app, and enable APM. Ensure that your app package name is the same as that configured in the APK file. If you need to enable APM for an existing app, make sure that the app package name in the APK file is the same as that configured in AppGallery Connect when the app is created.
Then select an app under My projects, go to Quality > APM, and click Enable.
{
"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.2 Downloading and Adding the JSON File
Create an Android project in Android Studio. The package name must be the same as that in AppGallery Connect.
In AppGallery Connect, select an app under My projects, go to Project settings > App information, download agconnect-services.json, and place the file in the app directory of your Android project.
2.3 Integrating the APM Plug-in and the APM SDK
To configure the SDK address, open your Android project, and configure the following content in the project-level build.gradle file.
Code:
buildscript {
repositories {
// Configure the following address:
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
// Configure the following address:
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath 'com.huawei.agconnect:agconnect-apms-plugin:1.3.1.300'
}
}
allprojects {
repositories {
// Configure the following address:
maven {url 'https://developer.huawei.com/repo/'}
}
}
Open the app-level build.gradle file, and configure the following content.
Code:
// Configure the following address:
apply plugin: 'com.huawei.agconnect'
apply plugin: 'com.huawei.agconnect.apms'
dependencies {
// Configure the following address:
implementation 'com.huawei.agconnect:agconnect-apms:1.3.1.300'
}
2.4 Configuring the Obfuscation File
Find the app-level proguard-rules.pro file (confusion configuration file), and add the following items:
Code:
-keep class com.huawei.agconnect.**{*;}
-dontwarn com.huawei.agconnect.**
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
-keepattributes Exceptions, Signature, InnerClasses, LineNumberTable
For how to find the file, see the following figure.
2.5 Packaging the App for Testing
After integration, click Sync in the upper right corner of your project in Android Studio to package and run your app on an Android device. Then, you can view the data in AppGallery Connect.
For more data, you can install and run the app on multiple devices.
3. Viewing Performance Data and ANR Data
Once you have run your app on a device, go back to AppGallery Connect. Find the app under My projects, go to Quality > APM, and view its performance data during testing.
As mentioned before, the performance data that you can view is diverse. The following is a sample report for your reference:
3.1 Overview
3.2 App Analysis
3.3 ANR Analysis
3.4 Network Analysis
4. Summary
In only 4 steps, you can integrate the HUAWEI AppGallery Connect APM SDK without coding, to implement comprehensive app performance monitoring.
The APM analysis report provides detailed device, log, and performance information recorded when an issue occurs. This real-time report drives app operations based on data and provides abundant information for app optimizations. App R&D and operations personnel no longer need to spend much time on locating and reproducing performance problems.
For more details, check:
AppGallery Connect APM development guide:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-apms-introduction

How to Build Hotel booking application using HMS Kits-part-1(Account & Ads Kit)

Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article I have implemented Account kit and Ads Kit. User can login through Huawei Id.
{
"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"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Account and Ads Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
Code:
<manifest xlmns:android...>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
</manifest>
3. Refer below URL for cross-platform plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001051088628-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: hotelbooking
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_ads:
path: ../huawei_ads/
huawei_account:
path: ../huawei_account/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Account kit
Account kit allows users to login their applications conveniently, quickly and simple login functionalities to the 3rd party applications.
If you examine Account Kit’s Official Huawei resources on internet, it also appears that they imply the simplicity, fastness and security. We can make use of following observation to understand where this fastness and simplicity is originated.
Service Features
Quick and standard
Huawei Account Kit allows you to connect to the Huawei ecosystem using your HUAWEI ID from a range of devices. This range of devices is not limited with mobile phones, you can also easily access applications on tablets, wearables, and smart displays using Huawei ID.
Massive user base and global services
Huawei Account Kit serves 190+ countries and regions worldwide. Users can also use HUAWEI ID to quickly sign in to apps. For details about supported regions/countries, please refer here from official documentation.
Secure, reliable, and compliant with international standards
Complies with international standards and protocols (such as OAuth2.0 and OpenID Connect), and supports two-factor authentication to ensure high security.
Integration
Signing-In
To allow users securely signing-in with Huawei ID, you should use signIn method of HMSAccount module. When this method called for the first time for a user, a Huawei ID authorization interface will be shown Once signIn successful, it will return AuthHuaweiID object.
Code:
void _signInHuawei() async {
final helper = new HmsAuthParamHelper();
helper
..setAccessToken()
..setIdToken()
..setProfile()
..setEmail()
..setAuthorizationCode();
try {
HmsAuthHuaweiId authHuaweiId =
await HmsAuthService.signIn(authParamHelper: helper);
StorageUtil.putString("Token", authHuaweiId.accessToken);
Navigator.push(context,MaterialPageRoute(builder: (context) => HomePageScreen()),
);
} on Exception catch (e) {}
}
Signing-Out
signOut method is used to allow user signing-out from app, it does not clear user information permanently.
Code:
void signOut() async {
try {
final bool response = await HmsAuthService.signOut();
} on Exception catch (e) {
print(e.toString());
}
}
ADs kit
Nowadays, traditional marketing has left its place on digital marketing. Advertisers prefer to place their ads via mobile media rather than printed publications or large billboards, this way they can reach their target audience more easily and they can measure their efficiency by analyzing many parameters such as ad display and the number of clicks.
HMS Ads Kit is a mobile service that helps us to create high quality and personalized ads in our application. It provides many useful ad formats such as native ads, banner ads and rewarded ads to more than 570 million Huawei device users worldwide.
Advantages
1. Provides high income for developers.
2. Rich ad format options.
3. Provides versatile support.
1. Banner Ads are rectangular ad images located at the top, middle or bottom of an application’s layout. Banner ads are automatically refreshed at intervals. When a user taps a banner ad, in most cases the user is taken to the advertiser’s page.
2. Rewarded Ads are generally preferred in gaming applications. They are the ads that in full-screen video format that users choose to view in exchange for in-app rewards or benefits.
3. Native Ads are ads that take place in the application’s interface in accordance with the application flow. At first glance they look like a part of the application, not like an advertisement.
4. Interstitial Ads are full screen ads that cover the application’s interface. Such that ads are displayed without disturbing the user’s experience when the user launches, pauses or quits the application.
5. Splash Ads are ads that are displayed right after the application is launched, before the main screen of the application comes.
Huawei Ads SDK integration Let’s call HwAds.init() in the initState()
Code:
@override
void initState() {
super.initState();
HwAds.init();
}
Load Banner Ads
void loadAds() {
BannerAd _bannerAd;
_bannerAd = createAd()
..loadAd()
..show();
}
BannerAd createAd() {
return BannerAd(
adSlotId: "testw6vs28auh3",
size: BannerAdSize.s320x50,
adParam: new AdParam());
}
Load Native Ads
Code:
NativeAdConfiguration configuration = NativeAdConfiguration();
configuration.choicesPosition = NativeAdChoicesPosition.bottomRight;
Container(
height: 100,
margin: EdgeInsets.only(bottom: 10.0),
child: NativeAd(
adSlotId: "testu7m3hc4gvm",
controller: NativeAdController(
adConfiguration: configuration,
listener: (AdEvent event, {int errorCode}) {
print("Native Ad event : $event");
}),
type: NativeAdType.small,
),
),
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. The lengths of access_token and refresh_token are related to the information encoded in the tokens. Currently, access_token and refresh_token contains a maximum of 1024 characters.
3. This API can be called by an app up to 10,000 times within one hour. If the app exceeds the limit, it will fail to obtain the access token.
4. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Account kit and Ads kit in this article.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Account Kit URL
Ads Kit URL
Read full article
Garrygb said:
Hi! Thank you for share this information. I tried to build apps for my business using HMS kits but unfortunately have some problems with the main code and I can't find where this code error. Perhaps, I will try to ask for help from professional apps developers.
Click to expand...
Click to collapse
Hi can you please explain which kit you integrated in your application ,can you explain detail so that i can able to help you out to fix your problems
I deleted all projects and start new.

Integration of Huawei Analytics kit and Crash service in Navigation Glove IoT application Using Kotlin — Part 6

{
"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​
If you are new to series of this article, follow the below article.
Beginner: Integration of Huawei Account kit in Navigation Glove IoT application Using Kotlin - Part 1
Beginner: Integration of Huawei Map kit in Navigation Glove IoT application Using Kotlin - Part 2
Beginner: Integration of Huawei Site kit in Navigation Glove IoT application Using Kotlin - Part 3
Beginner: Integration of Huawei Direction API in Navigation Glove IoT application Using Kotlin - Part 4
Beginner: Connecting to Smart Gloves Using Bluetooth in Navigation Glove IoT application Using Kotlin - Part 5
Click to expand...
Click to collapse
In this article, we will learn how to integrate Analytics kit and Crash Service in Smart Glove application.
Adding Events with Huawei Analytics Kit
This guide walks you through the process of building application that uses Huawei Analytics Kit to trigger event and can find data on the console.
What You Will Build
You will build an application that triggers events, setting user properties, logging custom event etc.
Prerequisite​
About 10 minutes
A favorite text editor or IDE(For me Android Studio)
JDK 1.8 or later
Gradle 4+
SDK platform 19
Analytics Kit
What is Mobile analytics?
Mobile analytics captures data from mobile app, website, and web app visitors to identify unique users, track their journeys, record their behaviour, and report on the app’s performance. Similar to traditional web analytics, mobile analytics are used to improve conversions, and are the key to crafting world-class mobile experiences.
How to complete this guide
When a person says that I know theoretical concept, only when he/she knows the answer for all WH questions. To complete this guide, let’s understand all WH questions.
1. Who has to use analytics?
2. Which one to use?
3. What is Huawei Analytics kit?
4. When to use HMS Analytics kit?
5. Why to use analytics kit?
6. Where to use analytics Kit?
Once you get answer for all the above questions, then you will get theoretical knowledge. But to understand with result you should know answer for below question.
1. How to integrate Huawei analytics kit?
Who has to use the analytics kit?
The answer is very simple, the analytics kit will be used in the mobile/web application. So off course software developer has to use analytics kit.
Which one to use?
Since there are many analytics vendors in the market. But for mobile application I recommend Huawei analytics kit. Now definitely you will have question why? To answer this I’ll give some reasons.
Very easy to integrate.
Documentation is too good.
Community is too good. Response from community is so fast.
Moreover, it is very similar to other vendors, so no need to learn new things.
You can see events in real time.
What is Huawei Analytics kit?
Flutter Analytics plugin enables the communication between HMS Core analytics SDK and Flutter platform. This plugin exposed all the functionality which is provided by HMS core analytics SDK.
Huawei Analytics kit offers you a range of analytics models that helps you to analyse the users’ behaviour with predefined and custom events, you can gain a deeper insight into your users, products and content. It helps you to gain insight into that how users behave on different platforms based on the user behaviour events and user attributes reported through apps.
Huawei Analytics kit, our one-stop analytics platform provides developers with intelligent, convenient and powerful analytics capabilities, using this we can optimize apps performance and identify marketing channels.
Collect and report custom events.
Set a maximum of 25 user attributes.
Automate event collection and session calculation.
Preset event IDs and parameters.
When to use HMS Analytics kit?
Mobile app analytics are a developer’s best friend. It helps you gain understanding about that how users’ behaviour and app can be optimized to reach your goals. Without mobile app analytics, you would be trying out different things blindly without any data to back up your experiments.
That’s why it’s extremely important for developers to understand their mobile app analytics to track their progress while working towards achieving their goals.
Why to use analytics kit?
Mobile app analytics are essential to development process for many reasons. They give you insights into that how users are using your app, which parts of the app they interact with, and what actions they take within the app. You can use these insights to come up with an action plan to improve your product in future, like adding new features that the users seem to need, or improve existing ones in a way that would make the users lives easier, or removing features that the users don’t seem to use.
You’ll also gain insights into whether you’re achieving your goals for your mobile app, whether its revenue, awareness, or other KPIs, and then take the data you have to adjust your strategy and optimize your app to reach your further goals.
When it comes to why? Always everyone thinks about benefits.
Benefits of Analytics
App analytics helps you to drive ROI over every aspect of performance.
App analytics helps you to gather accurate data to better serve for customers.
App analytics allows you to drive personalized and customer-focused marketing.
App analytics allows you to track individual and group achievements of marketing goals from campaigns.
App analytics offers data-driven insights into issues concerning churn and retention.
Where to use analytics Kit?
This is very important question, because you already know that why to use the analytics kit. So, wherever you want understand about user behaviour, which part of the application users are using regularly, which functionality of the application users are using more. In the scenario you can use analytics kit in either mobile/web application you can use the analytics kit.
Crash Service
What is Huawei Crash service?
In this article, we will learn how to integrate Crash services of AppGallery in Pygmy collection finance application.
Huawei Crash is a realtime crash reporting tool that helps in tracking, prioritizing, and fix stability issues that compromise the quality of your app. Crashlytics also helps in troubleshooting and saves the debugging.
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.
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.
Why do we need the crash service?
Although apps have gone through rounds the tests before release considering the large user base diverse device models and complex network environment. It’s inevitable for apps to crash occasionally. Crashes compromise user experience, users may even uninstall app due to crashes and your app is not going to get good reviews.
You can’t get sufficient crash information from reviews to locate crashes, therefore you can’t resolve them shortly. This will severely harm your business. That’s why we need to use the crash services in our apps to be more efficient.
Now start with practical
Till now you understood theoretical concept of the analytics kit. Now let’s start with the practical example, to understand about practical we should get answer for the below question.
How to integrate Huawei analytics kit in Android finance application?
To achieve this you need to follow the steps.
1. Configure application on the AGC.
2. Client application development process.
Configure application on the AGC
Follow the steps.
Step 1: We need to register as a developer account in AppGallery Connect. If you are already developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on current location.
Step 4: Enabling Analytics Kit. Project setting > Manage API > Enable analytics kit toggle button.
Step 5: Generating a Signing Certificate Fingerprint.
Step 6: Configuring the Signing Certificate Fingerprint.
Step 7: Download your agconnect-services.json file, paste it into the app root directory.
Step 8: Choose Quality > Crash > Enable the crash service.
Client application development process
Follow the steps.
Step 1: Create Android application in the Android studio (Any IDE which is your favorite)
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
How to integrate Analytics Kit and Crash Service
1. Configure the application on the AGC.
2. Client application development process.
3. Testing a Splash Ad.
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Java:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hianalytics:5.1.0.300'
implementation "com.huawei.agconnect:agconnect-crash:1.6.0.300"
}
Root level gradle dependencies.
Java:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: To allow HTTP and HTTPS network requests on devices with targetSdkVersion 28 or later, configure the following information in the AndroidManifest.xml file:
XML:
<application
...
android:usesCleartextTraffic="true">
...
</application>
Analytics kit
HuaweiLog.kt
Java:
package com.huawei.navigationglove.analytics
import com.huawei.navigationglove.analytics.HuaweiLog
import android.os.Bundle
import android.util.Log
import java.lang.Exception
import java.util.ArrayList
import java.util.HashMap
class HuaweiLog {
var eventName: String? = null
private val data: HashMap<String, String>? = HashMap()
fun setEventName(eventName: String?): HuaweiLog {
this.eventName = eventName
return this
}
fun setKeyAndValue(key: String, value: String): HuaweiLog {
data!![key] = value
return this
}
fun toBundle(): Bundle {
val bundle = Bundle()
try {
if (data != null && data.size > 0) {
for ((key, value) in data) {
bundle.putString(key, value)
Log.d("Huawei", "$key $value")
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return bundle
} /*
public HuaweiLog setTestDescription(ArrayList list) {
testdata.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), list);
return this;
}*/
}
HuaweiAnalyticsClient.kt
Java:
package com.huawei.navigationglove.analytics
import android.content.Context
import android.util.Log
import com.huawei.hms.analytics.HiAnalytics
import com.huawei.hms.analytics.type.ReportPolicy
import com.huawei.hms.analytics.HiAnalyticsInstance
import java.lang.Exception
import java.lang.RuntimeException
import java.util.HashSet
class HuaweiAnalyticsClient private constructor() {
fun initAnalytics(context: Context?) {
mHuaweiAnalyticsClient = HiAnalytics.getInstance(context)
if (mHuaweiAnalyticsClient == null) {
Log.e(TAG, "Analytics Client could not be initialized.")
return
}
mHuaweiAnalyticsClient!!.setAnalyticsEnabled(true)
mHuaweiAnalyticsClient!!.setUserId("UserId")
mHuaweiAnalyticsClient!!.setAutoCollectionEnabled(true)
// Used to report an event upon app switching to the background.
val moveBackgroundPolicy = ReportPolicy.ON_MOVE_BACKGROUND_POLICY
// Used to report an event at the specified interval.
val scheduledTimePolicy = ReportPolicy.ON_SCHEDULED_TIME_POLICY
// Set the event reporting interval to 600 seconds.
scheduledTimePolicy.threshold = 600
val reportPolicies: MutableSet<ReportPolicy> = HashSet()
// Add the ON_SCHEDULED_TIME_POLICY and ON_MOVE_BACKGROUND_POLICY policies.
reportPolicies.add(scheduledTimePolicy)
reportPolicies.add(moveBackgroundPolicy)
// Set the ON_MOVE_BACKGROUND_POLICY and ON_SCHEDULED_TIME_POLICY policies.
mHuaweiAnalyticsClient!!.setReportPolicies(reportPolicies)
}
fun logEvent(log: HuaweiLog) {
if (mHuaweiAnalyticsClient == null) {
throw RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().")
}
try {
mHuaweiAnalyticsClient!!.onEvent(log.eventName, log.toBundle())
Log.d("Huawei", log.eventName!!)
} catch (e: Exception) {
Log.d(TAG, "Huawei analytics failed" + e.message)
}
}
/* public void putHuaweiUserProperty(HuaweiUserProperty.KeyName propertyKey, String value) {
if (mHuaweiAnalyticsClient == null) {
throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
}
try {
mHuaweiAnalyticsClient.setUserProfile(propertyKey.textValue(), value);
} catch (Exception e) {
Log.d(TAG, "Huawei analytics failed", e);
}
}*/
fun setHuaweiUserId(userId: String?) {
if (mHuaweiAnalyticsClient == null) {
throw RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().")
}
if (userId == null) {
mHuaweiAnalyticsClient!!.setUserId(null)
return
}
mHuaweiAnalyticsClient!!.setUserId(userId)
}
companion object {
private val TAG = HuaweiAnalyticsClient::class.java.simpleName
private var ourInstance: HuaweiAnalyticsClient? = null
private var mHuaweiAnalyticsClient: HiAnalyticsInstance? = null
val instance: HuaweiAnalyticsClient?
get() {
if (ourInstance == null) {
ourInstance = HuaweiAnalyticsClient()
}
return ourInstance
}
}
}
AnalyticUtils.kt
Java:
package com.huawei.navigationglove.analytics
import android.util.Log
import java.lang.Exception
object AnalyticUtils {
private val TAG = AnalyticUtils::class.java.simpleName
fun logHuaweiAnalyticEvent(huaweiLog: HuaweiLog) {
try {
HuaweiAnalyticsClient.instance!!.logEvent(huaweiLog)
Log.d(TAG, "Huawei analytics $huaweiLog")
} catch (e: Exception) {
Log.d(TAG, "Huawei analytics failed")
}
}
}
Crash Report
Java:
//AGConnectCrash.getInstance().testIt(this)
AGConnectCrash.getInstance().enableCrashCollection(true)
AGConnectCrash.getInstance().setUserId("Add user ID");
AGConnectCrash.getInstance().log(Log.DEBUG, "set debug log.");
AGConnectCrash.getInstance().log(Log.INFO, "set info log.");
AGConnectCrash.getInstance().log(Log.WARN, "set warning log.");
AGConnectCrash.getInstance().log(Log.ERROR, "set error log.");
AGConnectCrash.getInstance().setCustomKey("stringKey", "Hello world");
AGConnectCrash.getInstance().setCustomKey("booleanKey", false);
AGConnectCrash.getInstance().setCustomKey("doubleKey", 1.1);
AGConnectCrash.getInstance().setCustomKey("floatKey", 1.1f);
AGConnectCrash.getInstance().setCustomKey("intKey", 0);
AGConnectCrash.getInstance().setCustomKey("longKey", 11L);
Result​
Analytics​
Crash Service​
Tips and Tricks​
Make sure you are already registered as a Huawei developer.
Make sure you have added the agconnect-services.json file to the app folder.
Make sure you have added the SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Make sure you added agconnect-service.json file.
Add internet permission in AndroidManifest.xml
Add the below code to download the HMS core apk
Conclusion​
In this article, we have learnt the integration of the Huawei Analytics kit and Crash service in Smart Glove application using Android Studio and Kotlin. And also we have learned how to download crash report and also we have learnt the tracking the analytics data on the console.
Reference​
Analytics Kit - Official document
Huawei Crash – Official document
Analytics Kit – Training Video
Huawei Crash – Training Video

Categories

Resources