Hello everyone, in this article I am going to talk about Crash services which one of the AppGallery Connect 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"
}
What is the crash service ?
The crash service of AppGallery Connect reports crashes automatically and allows crash analysis after integrating the crash service, your app will automatically report crashes to AppGallery Connect for it to generate crash reports in real time. The abundant information provided in reports will help you locate and resolve crashes.
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 you 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 can we integrate Crash service ?
It’s piece of cake ! , you only need to integrate the Crash SDK to your app. Then the SDK can implement related functions without any coding. I’m going to tell you how to implement the SDK in progressive section.
Getting Started on Crash Service
There are some procedures that you need to apply it into your own app.Here is the following steps ,go for it;
1-Integrating the AppGallery Connect SDK
You will find out whole necessary information about how to integrate the SDK on AppGallery Connect.
2-Enabling HUAWEI Analytics Kit
The Crash service uses capabilities of HUAWEI Analytics Kit when reporting crash events. Therefore, you must enable HUAWEI Analytics Kit before integrating the Crash SDK. For details, please refer to Service Enabling.
3-Integrating HUAWEI Analytics Kit
Before using HUAWEI Analytics Kit, you must integrate it by adding the following code to the app-level build.gradle file (usually in the app directory):
Java:
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
4-Integrating the Crash SDK
Add the following code to the app-level build.gradle file (usually in the app directory) to integrate the Crash SDK:
Java:
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.huawei.agconnect:agconnect-crash:1.4.1.300"
}
After applying these steps, don’t forget to click on “Sync Now” button on the right top to rebuild with updated version of your project.
AndroidManifest Permission
Also,you need to add these below permission commands into your Androidmanifest.xml.
Java:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.agccrash.huawei">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.huawei.permission.SECURITY_DIAGNOSE"/>
</manifest>
Code Development Part
You can see piece by piece code blocks in MainActivity.java
Add the code for calling the AGConnectCrash.testIt method to trigger a crash when the makeCrash button is tapped.
Java:
Button btn_crash = findViewById(R.id.btn_crash);
btn_crash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AGConnectCrash.getInstance().testIt();
}
});
Add the code for calling the AGConnectCrash.enableCrashCollection method to enable crash data reporting when the CrashCollectionON button is tapped.
Java:
findViewById(R.id.enable_crash_on).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().enableCrashCollection(true);
}
});
Add the code for disabling crash data reporting when the CrashCollectionOFF button is tapped.
Java:
findViewById(R.id.enable_crash_off).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().enableCrashCollection(false);
}
});
Add the code for calling AGConnectCrash.setUserId to define a custom user ID, calling AGConnectCrash.log to record custom logs, and calling AGConnectCrash.setCustomKey to define a custom key-value pair when the CustomReport button is tapped.
Java:
findViewById(R.id.CustomReport).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AGConnectCrash.getInstance().setUserId("testuser");
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);
}
});
Here is the all MainActivity.xml layout, it creates application interface.
Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/btn_crash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="makeCrash" />
<Button
android:id="@+id/enable_crash_off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CrashCollectionOFF" />
<Button
android:id="@+id/enable_crash_on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CrashCollectionON" />
<Button
android:id="@+id/CustomReport"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="CustomReport" />
</LinearLayout>
</LinearLayout>
The app interface you will see after applying xml to your own project is as follows.
So, we completed code development part, the next step is tracking and analysing results at AppGallery Connect ,after executing your project.
Enabling Crash Service On AppGallery Connect
After signing AppGallery Connect ,you need to follow these steps to enable crash service, if you are going to use it first time.
My project →Project Settings → Quality → Enable Now
How can we resolve the existing crashes ?
With signing in to AppGallery Connect ,you can check crash indicators including number of crashes, number of affected users and crash rate. You can filter date by time ,OS, app version, device type and other criteria to find the crash you want to resolve. In addition, you can check the details of the crash, locate the crash accordingly or directly go to the code where the crash occurs based on the crash stack and resolve the crash.
What is crash notification ?
The crash service will monitor your app in real time for crashes, When a critical crash occurs, if you have enabled the notification function, you will receive email notifications , so you can resolve them promptly.
How to Enable Crash Notifications ?
Please follow the below steps to enable crash notifications.
1. Sign in to AppGallery Connect and select Users and permissions.
2. Go to User > Personal information.
3. In the Notification area, select the check boxes under Email and SMS message for Crash notification (Notify me of a major crash) and click Save.
Monitoring & Analyzing Crash Service Test Result
After completing configuration process, you can see the results for your crash services.
In “Statistics ” tab, you will find out some outputs about crash. Such as;
How much times your app crashed,
Crash Rate,
Affected Users,
In time type
Additionally, you can select “Add Filter” on left top and check out the result as;
Operating System
App version,
Device
However, you can customize the threshold with clicking on “Set crash notification”.
You can also download report by clicking on “Download Report” to verify in .csv format the all crash results.
In ”Problems ” tab, you can view main problem of crash’ occuring reaason.Additively, can check out ;
Event Type,
Event,
Affected User,
Last occurence time.
After clicking on the name of the problem which is “java.lang.NullPointerException” here, you will get a chance to examine in detail.
In below table, you will have information to check such as;
Stack,
Logs,
Status,
Information.
Now we are going to explain above matters ,after that jump into “Search by User” tab.
In “Logs” tab , you can go through logs by filtering according to ;
All
Debug,
Info,
Warning
Error
Also you can get search with using the box named as “Enter a keyword”.
In “Status” tab , To obtain the app status in which a crash occurs, you can add a custom “key-value” pair to record the status. Actually here, you will have examine your own custom values that you created to occur crash.
In “Information” tab, you take a look at information about your ;
App
Operating System
Device
In “Search by user” tab, you will find out some outputs about crash’s ;
Occuring time,
User ID,
Event type,
Problems
Customizing a Crash Report
if you want , you can create your own crash report by customizing these red marked area parameters.So that your analyz will be more efficient and understandable.
FAQ’s
Q:Can I get export the all crash reports from AppGallery Connect ?
A:Yes sure, you can download as report .csv format in your own AGC crash page.
Q:Can I see through AGC that my application has been crashed for whatever reason?
A:Yes you can , clicking on through Problems tab, you will see 4 different tab named as Stack, Logs, Status and Information, each tab will give you different solution about what you are looking for
Q:Why can’t ı see the crash report immediately in AGC ,when I run the test in my app ? Is there any duration to see and how long data is stored ?
A:The reflection of the test report to you is at least 1 minute on average, and this data provides you with the results of hourly, 24-hour and 7-day, 30-day and 90-day data.
We have come to the end of my article, I hope what I mentioned will be useful to you, see you in my next article, I wish you all have a nice day…
References
https://developer.huawei.com/consum...Gallery-connect-Guides/agc-crash-introduction
Very useful.
Can we track activity names , where exactly crash happens and is it possible to track runtime exceptions?
Related
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.
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
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.
Introduction
Hello everyone. This article is second part is Huawei Game Service blog series. In the first part, I’ve give some detail about Game Service and I will give information about achievements, and events.Also I've explain how to use it in the your mobile game app with the MVVM structure.
You can find first part of the Game Service blog series on the below.
How to Use Game Service with MVVM / Part 1 — Login
{
"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"
}
What Is Achievement?
Achievements are a great way to increase player engagement within your game and to give players greater incentives to continue playing the game. An achievement can represent a player’s accomplishments (for example, number of defeated players or completed missions) or the skills the player has acquired. You can periodically add achievements to keep the game fresh and encourage players to continue to participate.
Achievement information must have been configured in AppGallery Connect. For details, please refer to Configuring Achievements.
Before calling achievement APIs, ensure that the player has signed in.
The device must run EMUI 10.0 or later, and have HUAWEI AppAssistant 10.1 or later installed, in order to support achievements display.
To use the achievement feature, users need to enable Game Services on HUAWEI AppGallery (10.3 or later). If a user who has not enabled Game Services triggers achievement API calling, the HMS Core SDK redirects the user to the Game Services switch page on HUAWEI AppGallery and instructs the user to enable Game Services. If the user does not enable Game Services, result code 7218 is returned. Your game needs to actively instruct users to go to Me > Settings > Game Services on AppGallery and enable Game Services, so the achievement feature will be available.
How To Create An Achievement?
Achievements are created on the console. For this, firstly log-in Huawei AGC Console.
Select “My Apps” -> Your App Name -> “Operate” -> “Achievements”
In this page, you can see your achievements and you can create a new achievement by clicking “Create” button.
After clicked “Create” button, you will see detail page. In this page you should give some information for your achievement. So, an achievement can contain the following basic attributes:
ID: A unique string generated by AppGallery Connect to identify an achievement.
Name: A short name for the achievement that you define during achievement configuration (maximum of 100 characters).
Description: A concise description of the achievement. Usually, this instructs the player how to earn the achievement (maximum of 500 characters).
Icon: Displayed after an achievement is earned. The icon must be 512 x 512 px, and in PNG or JPG format, and must not contain any words in a specific language. The HMS Core SDK will automatically generate a grayscale version icon based on this icon and use it for unlocked achievements.
Steps: Achievements can be designated as standard or incremental. An incremental achievement involves a player completing a number of steps to unlock the achievement. The predefined number of steps is known as the number of achievement steps.
List order: The order in which the current achievement appears among all of the achievements. It is designated during achievement configuration.
State: An achievement can be in one of three different states in a game.
Hidden: A hidden achievement means that details about the achievement are hidden from the player. Such achievements are equipped with a generic placeholder description and icon while in a hidden state. If an achievement contains a spoiler about your game that you would like not to reveal, you may configure the achievement as hidden and reveal it to the payer after the game reaches a certain stage.
Revealed: A revealed achievement means that the player knows about the achievement, but has not yet earned it. If you wish to show the achievement to the player at the start of the game, you can configure it to this state.
Unlocked: An unlocked achievement means that the player has successfully earned the achievement. This state is unconfigurable and must be earned by the player. After the player achieves this state, a pop-up will be displayed at the top of the game page. The HMS Core SDK allows for an achievement to be unlocked offline. When a game comes back online, it synchronizes with Huawei game server to update the achievement’s unlocked state.
After type all of the necessary information, click the “Save” button and save. After saving, you will be see again Achievement list. And you have to click “Release” button for start to using your achievements. Also, you can edit and see details of achievements in this page. But you must wait 1–2 days for the achievements to be approved. You can login the game with your developer account and test it until it is approved. But it must wait for approval before other users can view the achievements.
Listing Achievements
1.Create Achievement List Page
Firstly, create a Xml file, and add recyclerView to list all of the achievements. You can find my design in the below.
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:id="@+id/relativeLay"
android:layout_marginBottom="50dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Achievements"
android:textSize="25dp"
android:textAllCaps="false"
android:gravity="center"
android:textColor="#9A9A9B"
android:fontFamily="@font/muli_regular"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvFavorite"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"/>
</RelativeLayout>
2. Create AchievementsViewModel class
AchievementsViewModel class will receive data from View class, processes data and send again to View class.
Firstly create a LiveData list and ArrayList to set achievemets and send to View class. Create getLiveData() and setLiveData() methods.
Finally, create a client for achievements. And create a method to get all Achievements. Add all of the achievements into arrayList. After than, set this array to LiveData list.
Yo can see AchievementsViewModel class in the below.
Code:
class AchievementsViewModel(private val context: Context): ViewModel() {
var achievementLiveData: MutableLiveData<ArrayList<Achievement>>? = null
var achievementList: ArrayList<Achievement> = ArrayList<Achievement>()
fun init() {
achievementLiveData = MutableLiveData()
setLiveData();
achievementLiveData!!.setValue(achievementList);
}
fun getLiveData(): MutableLiveData<ArrayList<Achievement>>? {
return achievementLiveData
}
fun setLiveData() {
getAllAchievements()
}
fun getAllAchievements(){
var client: AchievementsClient = Games.getAchievementsClient(context as Activity)
var task: Task<List<Achievement>> = client.getAchievementList(true)
task.addOnSuccessListener { turnedList ->
turnedList?.let {
for(achievement in it){
Log.i(Constants.ACHIEVEMENT_VIEWMODEL_TAG, "turned Value : " + "${achievement.displayName}")
achievementList.add(achievement!!)
}
achievementLiveData!!.setValue(achievementList)
}
}.addOnFailureListener {
if(it is ApiException){
Log.i(Constants.ACHIEVEMENT_VIEWMODEL_TAG, "${(it as ApiException).statusCode}")
}
}
}
}
3. Create AchievementsViewModelFactory Class
Create a viewmodel factory class and set context as parameter. This class should be return ViewModel class.
Code:
class AchievementsViewModelFactory(private val context: Context): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return AchievementsViewModel(context) as T
}
}
4. Create Adapter Class
To list the achievements, you must create an adapter class and a custom AchievementItem design. Here, you can make a design that suits your needs and create an adapter class.
5. Create AchievementsFragment
Firstly, ViewModel dependencies should be added on Xml file. We will use it as binding object. For this, open again your Xml file and add variable name as “viewmodel” and add type as your ViewModel class directory like that.
XML:
<data>
<variable
name="viewmodel"
type="com.xxx.xxx.viewmodel.AchievementsViewModel" />
</data>
Turn back AchievemetsFragment and add factory class, viewmodel class and binding.
Code:
private lateinit var binding: FragmentAchievementsBinding
private lateinit var viewModel: AchievementsViewModel
private lateinit var viewModelFactory: AchievementsViewModelFactory
Real full article
Tips & Tricks
Remember that each success and event has a different ID. So, you must set the ID value of the event or achievement you want to use.
You must wait until the approval process is complete before all users can use the achievements and events.
Conclusion
Thanks to this article, you can create event and achievement on the console. Also, thanks to this article, you can grow and list your events.
In the next article, I will explain Leaderboard, Saved Games and give an example. Please follow fourth article for develop your game app with clean architecture.
References
HMS Game Service
Read full article here
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!!!