[AppsUP] Frequently Asked Questions About Huawei Push Kit - Huawei Developers

More information about the contest, you can visit HUAWEI Developer Forum.​
The AppsUP contest has already been launched more than two weeks. Many friends of mine have taken part in it already. And they unexpectedly meet many difficulties in the process of developing the apps. I believe many developers are the same. Today I want to share the frequently asked questions of Push Kit with you.
Q: How to configure the Huawei platform to receive notifications on all devices that have my application installed?
A: Please select All in Push Scope to send to all devices.
Q: PushKit take long time to be received on testing mode ?
A: These are the main issues of slowness. If you encounter the same problem, you can try to trace the issue according to the following list:
Sending time:
Receiving time:
SN number of the phone (dial *#06#):
appId:
name of apk:
Q: Test the ringtone of the customized notification channel on the Android client. But the message still the default marketing channel is used instead of the customized notification channel. Therefore, the customized ringtone is not played.
A: When creating a customized channel, you need to set the sound. Check whether the sound is set during channel creation. The ringtone file must be stored in the /res/raw directory of the application. Ensure that the file is stored in the correct location as required. For details, see the sound field description of https://developer.huawei.com/consumer/en/doc/development/HMS-References/push-sendapi
Ensure that the sound field is the same as the sound file name in the code,
The default sound field must be set to false. Finally, with regard to the level of messages sent, if the message level is judged to be average, the sound will be the default system sound.
Q: Failed to obtain the token ID after Huawei Push is integrated.
A: The APIClient object may be invalid. Check the code for initializing the APIClient object,
1. Choose Settings > Apps > App Manager, search for Huawei Mobile Services, clear the cache, check the update, and try to obtain the token again. For non-Huawei phones, install the latest version of Huawei Mobile Services (APK).
2. If the EMUI version is 10 or later, getToken is returned. If the EMUI version is earlier than 10, onNewToken is returned.
Q: Upgrading the Xamarin version from 3.2 to 4 is it going to affect the Integration of Push Kit?
A: Version upgrade should not affect the integrations, but if the upgrade causes compatibility version issues, Microsoft recommends remove all packages and re-add Xamarin.
This can be a reference: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/troubleshooting/
And if the CP wants to upgrade, is better make a backup first
Q: I am trying to use push kit for sending notification to my app users. I want send notification using api method. But it shows "error_description": "missing required parameter: client_id".
A: Please check your client code. This error comes up when you have the client id missing.
Q: Why sometimes the app does not receive any new pushes
A: Firstly, collect the push logs:
1. Dial *#*#2846579#*#*
2. Background Setting-->Background Debug-->Open
3. Background Setting-->AP Log Setting-->Open
4. adb shell setprop log.tag.hwpush VERBOSE
5. adb logcat -v threadtime 1>d:\log.txt
6. Please try to reproduce the push problem
7. Ctrl+C to stop the step 5
Then, search "PushLog" from log.txt
1.If the result like "PushLog100101200", it means HMS push is the default system push channel
2.If the result like "PushLog40002310_HMS", it means HMS push is not the default system push channel. In this case, the push is not stable enough.
So, Check GMS available or not firstly, if GMS is available, then use GMS push, if not, if HMS is available, then use HMS push.
Note: For some Huawei Phone support both GMS and HMS, even if you unstall the GMS, HMS push will not automatically become the default system push channel.
Q: Huawei push SDK has been correctly integrated and can obtain the app ID from agconnect-servicesjson to obtain the token. 907135701:907135700 is displayed.
A: Check whether the debug and release versions of your app use different signature certificate
Q: The Message ”No manifest found” Is Displayed When the Push Demo Code Is Run.
A: This problem occurs when the agcp plug-in version is earlier than 1.2.1.301. You can solve this problem in the following ways.
Method 1: Upgrade the agcp plug-in to the latest version. Go to buildscript > dependencies and and change the agcp version.
Method 1: Add the following configuration to the end of the build.gradle file at the application level to disable the dependency of the agcp plug-in on the manifest file.
After the build.gradle file is modified, Sync Now is displayed in the upper right corner. Click Sync Now and wait until the synchronization is complete. Or details, see Integrating the HMS SDK in Preparations:
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/Preparations#h1-1575707420071
Q: Compilation Errors in React Native Version 0.59.8
A: Following is a sample build.gradle file that can successfully resolve the problematic modules in the description:
Code:
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 19
compileSdkVersion = 28
targetSdkVersion = 28
}
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
maven {url 'http://developer.huawei.com/repo/'}
}
}
I will supplement other frequently asked questions about this kit regularly.
If you also have other questions about this kit. Leave your comment below.

Related

[AppsUP] Frequently Asked Questions About Huawei Map Kit

More information about the AppsUP contest, you can visit HUAWEI Developer Forum.​
The AppsUP contest has already been online. Maybe many developers encounter the following questions in the process. Today I want to share the frequently asked questions of Map Kit with you. Hope they can help you.
Q: Can I transfer a mark in Google Map to HUAWEI Map?
A: The mark in Google Map cannot be transferred to HUAWEI Map as Google Map does not support data export.
Q: Huawei map not working after upload the app to Huawei gallery. If i installed the same apk directly to phone everything working perfectly.
A: The fingerprint signatures of the two apps are different. That means you can use them separately.
Q: I am using HMS Map kit in my application when i open the particular activity. i am getting some messages repeatedly and UI is getting hanged and ANR is happening.
A: This issue can occur when the UI thread is blocked.
There could be below reasons for this issue:
1> Not using the MapAsync for handlling the callback.
2> While using the MapInitializer, context is null.
3> This provided URL is not correct.
Please check below for the reference
https://developer.huawei.com/consumer/en/doc/development/HMS-References/hms-map-mapsinitializer
https://developer.huawei.com/consumer/en/doc/development/HMS-References/hms-map-return-codes
Q: Map is not rendering and displays white screen returns http status code 502
A: If HTTP status code 502 is returned, a network error has occurred. Check your network environment.
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/open-platform-error-0000001050121484-V5
Q: I find gesturing on Map Kit a bit difficult? Is there a solution to make the gesturing similar to what is available on the Google Maps?
A: Some check points for you:
1. Please download sample code and use SupportMapFragment by referring to sample code. Link: https://developer.huawei.com/consumer/en/doc/development/HMS-Examples/hms-map-v4-example
2. Also please update the HMS Core version to the lastest and try.
Q: I followed tutorial about Map Kit , i check everything are same with the tutorial but , my map still blank
A: 1. Check wether you declared app id in manifest.xml file; 2. Enable map service in AGC.
Q: Is it possible to tilt the map more than 45 degrees?
A: Different tilt angles are required for different zoom levels.
when zoom < 10: it not allowed to tilt.
when zoom >= 10: 0 <= tilt <= 45.
So when you set tile to 70f, it can be max to 45f.
Q: I am developing an app with flutter and I decided to link it to a map kit, I followed the documentation and I still get this black screen that shows blank cells and I can't fix this problem
A: You probably haven't set up your signature certificate fingerprint
Please have a look at this guide:
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/config-agc-0000001050296920
Q: map kit 'integrated with flutter' doesn't work with all mobile phones
A: For the build apk, you should config your build.gradle like this (https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201289420207900111&fid=0101187876626530001)
Q: I couldn't find the complete list of mapFeatures in MapStyle JSON. Can I know where can I obtain the MapStyle JSON with all the mapFeatures?
A: You can refer to the official website:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-map-style-customization-0000001050728424
There is also a Style Editor that can be used to generate the JSON files in a quick manner located at the bottom of the documentation.
Q: How to convert from com.huawei.hms.maps.model.PointOfInterest to com.huawei.hms.site.api.model.Site ?
A: You can use the Site Kit Place Details to obtain the site for a given POI
Code:
<p style="line-height: 1.5em;">override fun onPoiClick(poi: PointOfInterest) {
//Obtain a Search service Instance
val searchService = SearchServiceFactory.create(requireContext(),
URLEncoder.encode(API_KEY, "UTF-8") )
//Create the request for the given POI
val request = DetailSearchRequest()
request.setSiteId(poi.placeId)
// Create a search result listener.
val resultListener =
object : SearchResultListener<DetailSearchResponse?> {
// Return search results upon a successful search.
override fun onSearchResult(result: DetailSearchResponse?) {
var site: Site?=null
if (result == null || result.site.also { site = it } == null) {
return
}
//here you can get the site information
Log.i("SITE","${site?.formatAddress}")
}
// Return the result code and description upon a search exception.
override fun onSearchError(status: SearchStatus) {
Log.e(
"TAG",
"Error : " + status.errorCode + " " + status.errorMessage
)
}
}
searchService.detailSearch(request, resultListener)
}</p>
You can check the guide here:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/android-sdk-place-details-0000001050156636-V5
More information like above, follow me. You can get the updated collection about HMS Kits.
Any doubts or questions about this, you can leave your comment below.

Integrate AGC UI in 15 Minutes

More information like this, you can visit HUAWEI Developer Forum​
AGC UI is a one stop solution where multiple third party providers can be integrated using Huawei AGC Auth Service for authentication. AGC UI provides our user to login by any third party providers and we can validate their identity without any requirement to implement our own backend servers. AGC UI has many features which we can utilize:
1) Has similar functionality as Firebase UI
2) Provides user token validation at server side
3) User can login in and link multiple third party providers in an application.
4) Has a default theme, but can be customize easily according to our need.
5) It is an open source library
Need of AGC UI
1) Firebase UI will not work on HMS devices.
2) Firebase UI provides multiple providers sign in at a single place.
3) Required single UUID for multiple providers.
4) Developer has no longer require to focus on UI part, it saves lot of integration time.
How it works?
1) Client app request for the UI to AGC UI library.
2) Based on the selection of the provider's, UI will be shown to client App.
3) User select specific provider for Authentication.
4) AGC UI will request the selected provider authentication page.
5) Show the authorization page to user in browser.
6) User enters their credentials.
7) AGC Server authenticate the user and returns the SignInResult to the client app.
Instead of writing boiler plate codes for third party providers which we need in our application for our users to authenticate using Huawei Auth Service, AGC UI allows us to authenticate users through a number of different third party providers avoiding boiler plate codes, providing us with both variety and flexibility when it comes to authentication within our applications. In this article we will see two ways of integrating AGC UI in our application:
a) Default theme
b) Customization theme
Demo
{
"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"
}
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.300 or later.
3) Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things need to be done
1) Create a project in android studio.
2) Get the SHA Key. For getting the SHA key, refer this article.
3) Create an app in the Huawei AppGallery connect.
4) Enable Auth Service setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below class path dependencies in project build.gradle file:
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
10) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: ‘com.huawei.agconnect’
11) Enter the below permission in android manifest file
Code:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
12) Now Sync the gradle.
Common steps required
As I mentioned earlier there are two ways we can integrate AGC UI in our application but both the ways required to follow a common steps to work with AGC UI library:
Enabling Huawei account, email address and mobile number
1) Navigate to AGC UI Github repository
https://github.com/Huawei-DTSE-India-Delhi-NCR/AGC-UI-Auth
2) Select AGC-UI-AUTH-MODULE as shown below:
3) Download the code as shown below:
4) Open the your android project and make the following changes in the app build.gradle file:
Code:
minSdkVersion 17 dataBinding {
enabled = true
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
5) Import the downloaded AGC-UI-AUTH-MODULE library as dependencies using project structure settings in your project and after importing the module the app build.gradle file should look like this:
Code:
implementation project(path: ':agcbase')
implementation project(path: ':agccommon')
implementation project(path: ':agcfacebook')
implementation project(path: ':agcphone')
implementation project(path: ':agcemail')
implementation project(path: ':agcgoogle')
implementation project(path: ':agchuweiid')
6) Navigate to AGC console and select your project.
7) Select Auth Service under your project Build
8) Enable mobile number, email address Authentication mode.
9) Enable Huawei account and provide your APP ID and APP SECRET of your project as shown below:
Enabling Facebook
1) Navigate to Facebook developer console. If you have not registered yourself as a developer yet, then Facebook will ask you to register as a developer.
2) Create new app and select android as platform.
3) Provide your project package name and Key Hash. For key hash put the below code in onCreate method of your project and run the project:
Code:
private void getFbHashKey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.huawei.hmsui",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
4) After creating the app get the App ID and App Secret of Facebook.
5) Enable Facebook authentication mode and provide the App ID and App Secret in Auth Service.
6) Add following facebook configuration into your application string.xml file
Code:
<string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>
<string name="fb_login_protocol_scheme">YOUR_FACEBOOK_APP_SECRET </string>
Enabling Twitter
1) Navigate to Twitter developer console. If you have not registered yourself as a developer yet, then Twitter will ask you to register as a developer.
2) Create a new app.
3) Get the API key and API key Secret.
4) Enable Twitter authentication mode in Auth Service and provide the API key and API secret key shown below:
e) In order to avoid “Failed to get request token” error we need to provide twittersdk:// as Callback URLs, website URL, Terms and Service and Privacy Policy in twitter authentication settings section.
f) Add following twitter configuration into your application string.xml file.
Code:
<string name="twitter_api_key">YOUR_TWITTER_API_KEY</string>
<string name="twitter_api_secret">YOUR_TWITTER_API_KEY_SECRET </string>
Enabling Google
1) Go to Google Developer Console. If you have not registered yourself as a developer yet, then Twitter will ask you to register as a developer.
2) Create your project. Provide your package name and SHA1 key there and get the Client ID and Client Secret.
3) Enable Google authentication mode in Auth Service and provide the Client ID and Client Secret as shown below:
4) Add following Google configuration into your application string.xml file.
Code:
<string name="google_client_id">YOUR_GOOGLE_CLIENT_ID </string>
<string name="redirect_uri">Your_PACKAGE_NAME:/oauth2callback</string>
5) Add following into your application manifest file.
Code:
<activity android:name="net.openid.appauth.RedirectUriReceiverActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="YOUR_PACKAGE_NAME" />
</intent-filter>
</activity>
6) Add below dependency in app gradle
Code:
implementation 'net.openid:appauth:0.2.0'
Default theme of AGC UI
The default theme of AGC UI is nothing but the default user interface which is provided by the library. Following are the steps to use the default theme of AGC UI:
1) Comment or remove setContentViewMetho
2) Use initializeButton method to show or hide third party providers as shown below:
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main2);
initializeButton(true,true,true,true,true,true);
}
3) Enable app log and app name as shown below:
Code:
enableAppLogo(true);
enableAppName(true);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
appLogo( getResources().getDrawable(R.drawable.ic_body_builder),400,400);
appBackgroundColor("#fafafa");
appName("PANDAVAS",50,"#3e454f",typeface);
Byenabling them, we can provide our own app logo and name as shown above.
4) After user login using any provider the data we will receive in onActivityResult as shown below:
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data.getExtras() != null) {
Log.d(getClass().getName(), "RESPONSE IS " + data.getExtras().getString("response"));
Intent intent = new Intent(Main2Activity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
if(resultCode == Activity.RESULT_CANCELED){
// Do Anything
Toast.makeText(getApplicationContext(),"Canceled",Toast.LENGTH_LONG).show();
}
}
Result
Customization theme of AGC UI
We can also customize our own user interface using AGC UI. Following are the steps to customize:
1) Download the semi-circular radial menu library from the below link:
http://hasmukhbhadani.blogspot.com/2014/04/radial-menu-semi-circular-radial-menu.html
Get two files from this library that is SemiCircularRadialMenu and SemiCircularRadialMenuItem. Paste this two files in your project and modify them if you required.
2) Add the following code in our layout xml file:
Code:
<com.huawei.hmsui.arclib.SemiCircularRadialMenu
android:id="@+id/radial_menu"
android:layout_width="0dp"
android:layout_height="0dp"
android:padding="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
3) Add the following code in our Activity file:
Code:
// HUAWEI ID
mHuaweiId.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, HuaweiIdAuth.class), Constant.REQUEST_HU_SIGNIN_CODE);
}
});
Code:
// TWITTER LOGIN
mTwitter.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, TwitterAuth.class), Constant.REQUEST_TWITTER_CODE);
}
});
Code:
// GOOGLE LOGIN
mGoogle.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, GSignInActivity.class), Constant.REQUEST_GOOGLE_CODE);
}
});
Code:
// FACEBOOK LOGIN
mFacebook.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, FacebookAuth.class), Constant.REQUEST_FACEBOOK_CODE);
}
});
Code:
// EMAIL LOGIN
mHuaweiEmail.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, EmailAuthActivity.class), Constant.REQUEST_EMAIL_AUTH);
}
});
Code:
// PHONE LOGIN
mHuaweiPhone.setOnSemiCircularRadialMenuPressed(new SemiCircularRadialMenuItem.OnSemiCircularRadialMenuPressed() {
@Override
public void onMenuItemPressed() {
startActivityForResult(new Intent(MainActivity.this, PhoneRegisterActivity.class), Constant.REQUEST_PHONE_AUTH);
}
});
In the above code using startActivityForResult we can get the login functionality for providers.
4) After user login using any provider the data we will receive in onActivityResult same as default theme.
Result
AGC UI vs Firebase UI
Limitation of AGC UI
1) It will not support google sign in with underscore(_) in package name like:
com.example.demotest(supported)
com.example.demo_test(unsupported)
2) Update Email and update phone is not working in AGC for third party providers.
3) AGC UI only works for Android.
What we learn?
We learn how to integrate AGC UI and create two ways of login. It is an open source library so go crazy and build something useful.
GitHub
Very soon I am going to post the entire code on GitHub. So come back again to check it out.
FAQ
Question 1: While google signin we are getting Uri Mismatch Error
Answer:
1) Check redirectUri and client id in string.xml. RedirectUri in your string xml must be your_package_name+:/oauth2callback and client id must be android clientid.
2) Open AndroidManifest.xml and Check for android scheme in intent-filter of RedirectUriReceiverActivity. It must be your_package_name.
Question 2: While google signin getting 401(Authorization Error)
Answer: Check google developer console and confirm you are using client id of same application/project.
Question 3: Third party provider authentication is successful, but not able to Signing in AGC
Answer:
1) Check for provider on AGC console, it is enabled or not.
2) Check your app's authentication mode details by following
AGC console > My Project > Build > Auth Service > specific provider
For more reference
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-service-introduction
https://github.com/Huawei-DTSE-India-Delhi-NCR/AGC-UI-Auth

Intermediate - How to Integrate HMS Kits into Hotel booking application (Analytics & Site 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 Analytics kit and Site Kit.
{
"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: Analytics and Site 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.
XML:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...
</manifest>
3. Refer below URL for cross-platform plugins. Download required 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/
huawei_site:
path: ../huawei_site/
huawei_analytics:
path: ../huawei_analytics/
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.
Analytics kit
Account kit is valuable in terms of analysis and reporting that we use frequently in our application. Using analytics we can check user behavior custom events and predefined events.
Service Features
By integrating the HMS Core Analytics SDK, you can:
1. Collect and report custom events through coding.
2. Set a maximum of 25 user attributes.
3. Automate event collection and session calculation with predefined event IDs and parameters.
HUAWEI Analytics Kit identifies users and collects statistics on users by an anonymous application identifier (AAID). The AAID is reset in the following scenarios:
1. Uninstall or reinstall the app.
2. The user clears the app data.
After the AAID is reset, the user will be counted as a new user.
There are 3 types of events:
Automatically collected
Predefined
Custom
Automatically collected events are collected from the moment you enable the kit in your code. Event IDs are already reserved by HUAWEI Analytics Kit and cannot be reused.
Predefined events include their own Event IDs which are predefined by the HMS Core Analytics SDK based on common application scenarios. The ID of a custom event cannot be the same as a predefined event’s ID. If so, you will create a predefined event instead of a custom event.
Custom events are the events that you can create for your own requirements.
Integration
What is AAID?
Anonymous device ID opened to third-party apps. Each app is allocated with a unique AAID on the same device, so that statistics can be collected and analyzed for different apps.
Code:
void getAAID() async{
String aaid = await mAnalytics.getAAID();
print(aaid);
}
Custom Events
Such events can be used to meet personalized analysis requirements that cannot be met by automatically collected events and predefined events.
Note: The ID of a custom event cannot be the same as that of a predefined event. Otherwise, the custom event will be identified as a predefined event
Adding Custom Events
In AppGallery Connect from left side panel open Huawei Analytics > Management > Events
Code:
void customEvent() async {
String name = "Custom";
dynamic value = {'customEvent': "custom Event posted"};
await _hmsAnalytics.onEvent(name, value);
}
Predefined Events
Such events have been predefined by the HMS Core Analytics SDK based on common application scenarios. It is recommended you use predefined event IDs for event collection and analysis.
Code:
void logEvent() async{
String name = HAEventType.SUBMITSCORE;
dynamic value = {HAParamType.SCORE: 15};
await mAnalytics.onEvent(name, value);
}
Site kit
This kit basically provide users with easy and reliable access to related locations and places. With the HMS Site kit we can provide them below features.
1. We can take place suggestions according to the keywords that we have determined.
2. According to the location of the user’s device, we can search for nearby places.
3. We can get detailed information about a location.
4. We can learn the human readable address information of a coordinate point.
5. We can learn the time period where a coordinate point is found.
HMS Site kit – Nearby Search
We can search for many places such as tourist attractions, restaurants, schools and hotels by entering information such as keywords, coordinates. Using this kit we can restrict to specific types using poiType, we can easily access many different information about places such as name, address, coordinates, phone numbers, pictures, address details. Within the Address Detail model, we can easily access information about the address piece by piece through different variables and change the way the address’ notation as we wish.
We need to create a NearbySearchRequest object to perform searching by keyword. We will perform the related search criteria on this NearbySearchRequest object.
While performing this operation, we need set many different criteria as we see in the code snippet. Let us examine the duties of these criteria one by one
1. Query: Used to specify the keyword that we will use during the search process.
2. Location: It is used to specify latitude and longitude values with a Coordinate object to ensure that search results are searched as closely to the location that we want.
3. Radius: It is used to make the search results within in a radius determined in meters. It can take values between 1 and 50000, and its default value is 50000.
4. CountryCode: It is using to limit search results according to certain country borders.
5. Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, the language of the query field we have specified in the query field is accepted by default. In example code snippet in above, the language of device has been added automatically in order to get a healthy result.
6. PageSize: Results return with the Pagination structure. This parameter is used to determine the number of Sites to be found in each page.
7. PageIndex: It is used to specify the number of the page to be returned with the Pagination structure.
Code:
void loadNearBy(String value) async {
SearchService service = new SearchService();
NearbySearchRequest searchRequest = NearbySearchRequest();
searchRequest.language = "en";
searchRequest.query = value;
searchRequest.poiType = LocationType.RESTAURANT;
searchRequest.location = Coordinate(lat: 12.976507, lng: 77.7356);
searchRequest.pageIndex = 1;
searchRequest.pageSize = 15;
searchRequest.radius = 5000;
NearbySearchResponse response = await service.nearbySearch(searchRequest);
if (response != null) {
setState(() {
mSitesList = response.sites;
});
}
}
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. Enable Auto refresh in AppGallery connect it will automatically update events in console
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Analytics kit and Site kit in this article. We have learned how to record events and monitor them in AppGallery Connect and also we have learned how to integrated site kit and how nearby search will work.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Analytics Kit URL
Site Kit URL
Read full article.

Troubleshooting for Huawei's App Performance Management SDK

I encountered a few issues in the process of integrating the APM SDK. In this post, I will share these cases for you, so that you will have a sense of how to resolve them.
Issue 1: Error "miss client id" Is Reported After the APM SDK Is Integrated​The detailed error message is as follows:
I/com.huawei.agc.apms: failed to fetch remote config: client token request miss client id, please check whether the 'agconnect-services.json' is configured correctly
Click to expand...
Click to collapse
Troubleshooting​By searching through the forum, I found that the issue is caused by the absence of the AppGallery Connect plugin. For details, please refer to this forum post.
To solve the problem, just add the following code to the app-level build.gradle file:
apply plugin: 'com.huawei.agconnect'
Click to expand...
Click to collapse
Issue 2: Cannot Find the Reported APM Logs on the Device​When the APM SDK is integrated, there was no app performance data on the App performance management page. I wanted to locate the problem based on the Logcat logs on the device.
However, I wasn't sure how to find the APM logs.
Troubleshooting​I checked the APM documentation and found out how to access the logs:
Open the AndroidManifest.xml file of the app, and add the meta-data element to application.
<application>
<meta-data
android:name="apms_debug_log_enabled"
android:value=" true" />
</application>
After the APM debug log function is enabled, you can use the Logcat log filter function com.huawei.agc.apms or apms to view the logs.
Please note that only the value of resultCode is 200 indicates that the data is reported successfully.
I/HiAnalyticsSDK: SendMission=> events PostRequest sendevent TYPE : oper, TAG : APMS, resultCode: 200 ,reqID:b639daae0490c378cf242544916a9c36
Click to expand...
Click to collapse
Issue 3: No Successfully Uploaded AMPS Logs in the Logcat.​The meta-data element has been added and set to true. The contains and sending logs can be viewed in the Logcat, with the exception of the successfully uploaded AMPS logs.
Troubleshooting​The check result shows that the agconnect-services.json file was downloaded before the APM service was enabled. This indicates that it needs to be updated.
Before the service was enabled, the JSON file contained only 29 lines. After the service was enabled, more parameters were added to the file that it has contained 52 lines.
Update the JSON file, and you'll be able to view the successfully uploaded AMP logs.
Issue 4: No APM Data Displayed in AppGallery Connect While Logs Are Available​When locating this problem, I found a log in which the result code is 200. However, still no APM data is available in AppGallery Connect.
The corresponding logs are as follows:
I/HiAnalyticsSDK: hmsSdk=> events PostRequest sendevent TYPE : maint, TAG : _hms_config_tag, resultCode: 200 ,reqID:842927417075465ab9ad990e2ce92646
Click to expand...
Click to collapse
Troubleshooting​The value of TAG in the preceding log is not APMS. Therefore, it cannot be the log that indicates that the APM data is successfully loaded.
I analyzed the logs and found some authentication failure logs.
E/HiAnalyticsSDK: HttpTransportCommander=> NE-004|IO Exception.timeout
D/HiAnalyticsSDK: HttpTransportCommander=> request times: 1
I/HiAnalyticsSDK: getPubKey=> result code : -102
Click to expand...
Click to collapse
After contacting Huawei technical support, I learned that the data reporting channel of the HiAnalyticsSDK used by APM has an authentication problem.
I went to My projects > HUAWEI Analytics in AppGallery Connect and enabled HUAWEI Analytics. After a while, the authentication was successful.
Issue 5: No Related Network Request Performance Data Is Displayed.​All of the performance data is normal with the exception of the network request data, which is not displayed in AppGallery Connect.
Troubleshooting​According to the official documentation, obtaining network request data depends on the APM plugin. The data can only be obtained after the APM plugin has been correctly integrated.
To integrate the plugin, do as follows:
In the project-level build.gradle file, add the following code in dependencies:
classpath 'com.huawei.agconnect:agconnect-apms-plugin:1.4.1.305'
In the app-level build.gradle file, add the following code:
apply plugin: 'com.huawei.agconnect.apms'

Implement Realistic 3D Rendering in Three Steps

The conventional method of rendering a 3D model and scene with realistic materials is often tedious, making it difficult to standardize into several, simple steps.
Let's see what this process requires:
First, a rich array of texture maps and material images should be prepared according to how detailed and complex the model and scene are. The more complex they are, the more time-consuming the process of collecting such maps and images will be. Of course you can turn to those available on the market, but they could be expensive.
Second, parameters that have to be created from scratch. Most 3D modeling programs require abundant parameters for rendering, and setting or controlling models via parameter adjustment.
Third, work experience. The demand for 3D modelers is increasing, emphasizing the skills and work experience necessary for 3D modeling. As models and scenes are becoming more diverse and delicate, the modeler has a bigger influence over the quality of the models.
Indeed, such requirements — if met — lead to a desirable result. They, however, are also daunting.
Fortunately, there is now an easier solution to this with the material generation capability from 3D Modeling Kit, which is easy-to-use and can create high-quality materials in just three steps.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
​The image on the left shows a complex scene containing multiple objects. Such a scene is common to see in a 3D game. To render it with materials, we just need to:
1. Use an RGB camera to collect images of real materials.
2. Input the images for material generation, which automatically generates the texture maps.
3. Use the maps for rendering.
​The material generation capability from 3D Modeling Kit utilizes AI to streamline and simplify the strenuous process of material generation and rendering, to improve the efficiency of creating 3D models at a lower cost. Specifically speaking, this capability offers the template materials that are created from the experience and material creation specifications of technical artists, to make such valuable assets reusable.
Introduction to Material Generation​
This capability enables your users to turn one or more RGB images into four physically based rendering (PBR) texture maps (the diffuse map, normal map, specular map, and roughness map), with just a tap, to help create true-to-life materials. This capability utilizes AI to create 3D materials for commercial use.
Specifications
Software and hardware requirements: an Android device with a standard RGB camera, instead of an RGB-D or light detection and ranging (LiDAR) sensor
Supported material types: concrete, marble, rock, gravel, brick, gypsum, clay, metal, wood, bark, leather, fabric, paint, plastic, composite material, and ground (including grass and sand)
Supported input images: have a resolution within the range of 1K to 4K, containing no seam, light spot, shade, or reflection.
Output texture maps: have a resolution of 1K (1024 x 1024 px) or 2K (2048 x 2048 px).
SDK size: 88 KB
Accuracy (SSIM): > 0.9
Application scenarios: The powerful material generation capability can be adopted in a wide range of scenarios, for example:
E-commerce: Use this capability to create 3D product models, delivering a more immersive online shopping experience to users.
Exhibition: Display lifelike 3D models of valuable items such as cultural exhibits.
Game: Create realistic wooden floors, tables, and walls for indoor scenes, to better immerse players.
Development Preparations​Integrating the HMS Core SDK​Add the AppGallery Connect configuration file of your app.
Add the agconnect-services.json file to your app after you have enabled 3D Modeling Kit.
Step 1. Sign in to AppGallery Connect and click My projects.
Step 2. Find your project and click the app that needs to integrate the HMS Core SDK.
Step 3. Go to Project settings > General information. In the App information area, click agconnect-services.json to download the configuration file.
Step 4. Copy the file to the app's root directory.
​Configuring the Maven Repository Address for the HMS Core SDK
Step 1. Open the project-level build.gradle file of your Android Studio project.
Step 2. Add the AppGallery Connect plugin and the Maven repository.
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
Go to buildscript > dependencies and add the AppGallery Connect plugin configuration, if the agconnect-services.json file has been added to the app configuration, if the agconnect-services.json file has been added to the app.
Code:
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}
Note that the Maven repository address cannot be accessed from a browser. It can only be configured in the IDE. If there are multiple Maven repositories, add the Maven repository address of Huawei as the last one.
Adding Build Dependencies
Step 1. Open the app-level build.gradle file.
​Step 2. Add build dependencies in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:modeling3d-material-generate:{version}'
}
Note: Replace {version} with the actual SDK version number. For details about the version number, please refer to Version Change History.
For example: implementation 'com.huawei.hms:modeling3d-material-generate:1.0.0.300'.
Step 3. Add the AppGallery Connect plugin configuration in either of the following methods:
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration.
id 'com.huawei.agconnect'
}
Defining Multi-language Settings​
If your app supports all the languages supported by the HMS Core SDK, skip the operation procedure in this section.
If your app supports only some of these languages, follow the operation procedure in this section to complete the required configuration.
a. Open the app-level build.gradle file.
b. Go to android > defaultConfig, add resConfigs, and configure the supported languages as follows:
Code:
android {
defaultConfig {
...
resConfigs "en", "zh-rCN", "Other languages supported by your app"
}
}
For details about the languages supported by the HMS Core SDK, please refer to Languages Supported by the HMS Core SDK.
Synchronizing the Project​After completing the preceding configuration, click the synchronization icon on the toolbar to synchronize the Gradle files.
​If an error occurs, check the network connection and the configuration in the build.gradle files.
Configuring Obfuscation Scripts​Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Step 1. Open the app-level obfuscation configuration file proguard-rules.pro of your project and add configurations to exclude the HMS Core SDK from obfuscation.
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
Adding Permissions​To use the material generation capability, declare the following permissions in the AndroidManifest.xml file:
Code:
<!-- Write texture map files to storage and read data to be processed from storage. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Connect to Internet for uploading images or downloading texture maps. -->
<uses-permission android:name="android.permission.INTERNET" />
Development Procedure​Before developing your app, you need to make necessary preparations. Ensure that the Maven repository address for the HMS Core SDK has been configured in your project, and the SDK of this service has been integrated.
1.Set an access token or use the API key in agconnect-services.json during app initialization for your app authentication.
(Recommended) Use the setAccessToken method to set an access token during initialization when the app is started. The access token does not need to be set again.
Code:
MaterialGenApplication.getInstance().setAccessToken("your AccessToken");
For details about how to obtain the access token, please refer to "Client Credentials" in OAuth 2.0-based Authentication.
Use the setApiKey method to set an API key during initialization when the app is started. The API key does not need to be set again.
Code:
MaterialGenApplication.getInstance().setApiKey("your api_key");
When you create an app in AppGallery Connect, an API key will be assigned to your app.
2.Create a material generation engine and configurator, and initialize the engine.
Code:
// Create a material generation engine and pass the current context.
Modeling3dTextureEngine engine = Modeling3dTextureEngine.getInstance(context);
// Create a material generation configurator.
Modeling3dTextureSetting setting = new Modeling3dTextureSetting.Factory()
// Set the working mode to AI.
.setTextureMode(Modeling3dTextureConstants.AlgorithmMode.AI)
.create();
3.Create a listener callback to process the image upload result.
Code:
Modeling3dTextureUploadListener uploadListener = new Modeling3dTextureUploadListener() {
public void onResult(String taskId, Modeling3dTextureUploadResult result, Object ext) {
// Obtain the image upload result.
if (result.isComplete()) {
// Process the upload result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during upload.
}
@Override
public void onUploadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
4.Upload the collected images to the cloud.
Code:
// Obtain the ID of a material generation task and pass it to the configurator.
Modeling3dTextureInitResult modeling3dTextureInitResult = engine.initTask(setting);
String taskId = modeling3dTextureInitResult.getTaskId();
if (taskId == null || taskId.equals("")) {
Log.e("", "get taskId error " + modeling3dTextureInitResult.getRetMsg());
} else {
// Set the upload listener.
engine.setTextureUploadListener(uploadListener);
// Upload the images in asynchronous mode, passing the task ID and directory of the images.
engine.asyncUploadFile(taskId, filePath);
}
5.Query the progress of an on-cloud material generation task.
Code:
// Create a material generation task processing instance and pass the current context.
Modeling3dTextureTaskUtils taskUtils = Modeling3dTextureTaskUtils.getInstance(context);
// Query the material generation progress.
Modeling3dTextureQueryResult queryResult = taskUtils.queryTask(taskId);
6.Create a listener callback to process the download result of generated texture maps.
Code:
Modeling3dTextureDownloadListener downloadListener = new Modeling3dTextureDownloadListener() {
public void onResult(String taskId, Modeling3dTextureDownloadResult result, Object ext) {
// Obtain the download result of generated texture maps.
if (result.isComplete()) {
// Process the download result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during download.
}
@Override
public void onDownloadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
7.Download the generated texture maps.
Code:
// Set the download listener.
engine.setTextureDownloadListener(downloadListener);
// Download the texture maps, passing the task ID and texture map path.
engine.asyncDownloadTexture(taskId, savePath);
8.Call the synchronous API to obtain the generated texture maps in real time.
Code:
// Call the synchronous API, passing the image file path, texture map path, and configurator.
int result = engine.syncGenerateTexture(filePath, downloadPath, setting);
9.Delete the material generation task.
Code:
int ret = taskUtils.deleteTask(taskId);
Amazing capability, right? To learn more about 3D Modeling Kit, check out:
References
Official website of 3D Modeling Kit
Development guide to the kit
HMS Core section on HUAWEI Developer Forum
GitHub and Gitee to obtain the open-source code for the kit
Stack Overflow where you can find solutions to integration-related problems

Categories

Resources