Tips for Creating a Link of App Linking Using the App Linking SDK - Huawei Developers

What Is App Linking​App Linking allows you to create redirection links that work across multiple platforms including Android, iOS, HarmonyOS, and web. With links of App Linking, you can redirect users to ads, or native app content that they can share with each other. You can create app links and send them to users, or allow users to share links dynamically generated in your app. Anyone who receives a link can tap it to access the specific app content.
Enabling App Linking and Integrating the App Linking SDK​1. Click My projects in AppGallery Connect, click your project card, and select your app for which you want to enable App Linking from the drop-down list on the top.
2. Go to Grow > App Linking. If it is the first time that you use the service, click Use now.
3. Enter the App Store ID and team ID used in your signing certificate, and then click ☑.
4. Go to Project settings > General information, and download the agconnect-services.plist file under App information.
5. Open the CLI and navigate to the location of your Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.
cd project-directory
pod init
6. Edit the Podfile to add the pod dependency AGConnectAppLinking.
target 'AGC-AppLinking-2' do
pod 'AGConnectAppLinking'
end
7. Install the pod and open the .xcworkspace file to view the project.
pod install
Designing the UI​You can create a page layout in your iOS project and design the UI according to the following figure. On the page, a link of App Linking can be received and displayed.
Requesting a URL Prefix​1. Go to Grow > App Linking. Click the URL prefixes tab and click New URL prefix.
2. In the Set domain name area, enter a URL prefix.
3. Click Next. The system automatically checks whether the URL prefix is available.
Creating a Link of App Linking in Your App​1. Import AGConnectCore and AGConnectAppLinking to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
import AGConnectCore
import AGConnectAppLinking
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AGCInstance.startUp()
return true
}
2. Create an object named AGCAppLinkingComponents, and set urlPrefix to the URL prefix requested in AppGallery Connect. Set deepLink. Set iOS app parameters, where iosBundleId is the app package name, and iosDeepLink is the redirection link to your iOS app.
let components = AGCAppLinkingComponents()
components.uriPrefix = "https://codelab.drcn.agconnect.link"
components.deepLink = "https://developer.huawei.com/consumer/cn"
components.iosBundleId = Bundle.main.bundleIdentifier
components.iosDeepLink = "AppLinking://ios/test2=456"
components.socialTitle = "AppLinking"
3. Call components.buildLongLink to generate and obtain a long link.
longLinkLabel.text = components.buildLongLink().absoluteString
4. Call components.buildShortLink to generate and obtain a short link.
components.buildShortLink { [self] (shortLink, error) in
if let e = error {
let alert = UIAlertController.init(title: "Error", message: e.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
shortAppLinking = shortLink?.url.absoluteString
shortLinkLabel.text = shortAppLinking
}
5. In the method of sharing a link, the short link, generated by the App Linking SDK, is copied to the system clipboard.
@objc func shareLink() {
UIPasteboard.general.string = shortAppLinking
}
Receiving a Link of App Linking in Your App​1. If you want the link of App Linking to be a custom URL, set a custom URL scheme under TARGETS > Info > URL Types in Xcode. Set URL Schemes to AppLinking.
2. Import AGConnectCore and AGConnectAppLinking to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
import AGConnectCore
import AGConnectAppLinking
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AGCInstance.startUp()
}
3. Call the AGCAppLinking.instance().handle method, and process the received link event in the callback.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
self.window?.rootViewController = nav
AGCInstance.startUp()
AGCAppLinking.instance().handle { (link, error) in
let deepLink = link?.deepLink
vc.getDeepLink(deeplink: deepLink)
}
self.window?.makeKeyAndVisible()
return true
}
4. Implement the application: openURL: options: method, and return the value of AGCAppLinking.instance().openDeepLinkURL(url).
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let isAppLinking = AGCAppLinking.instance().openDeepLinkURL(url)
return isAppLinking
}
Compiling and Testing Your App​1. In Xcode, run your app on a mobile phone or simulator.
2. Click Create App Linking to generate a long link and a short link using the App Linking SDK.
3. Click Share short App Linking to copy the short link to the clipboard.
4. Paste the short link to a browser and access the link. Click Open to launch your app as prompted.
Congratulations​Well done. You have successfully built an app that integrates App Linking of AppGallery Connect and learned how to:
Create a sharable link using the App Linking SDK.
Launch your app through the configured link and receive the deep link using the App Linking SDK.

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.

Getting Place Details with HMS Site Kit

If we briefly talk about what HMS Site Kit is, you can provide users to explore the world faster with Site Kit. You can search for locations by keywords, find places which are close to the specified coordinate point, get detailed information about a place and get suggestions for places by keyword.
We can get detailed information about a place with Place Detail Search, another feature of Site Kit. The only condition for this, we need to know Site model’s id value that belongs to the place we want to search.
Before I explain the use of Place Detail Search, I would like to share with you a function that we can use this feature.
Code:
fun placeDetail(siteId: String){
val searchService = SearchServiceFactory.create(context,
URLEncoder.encode(
"Your-API-KEY",
"utf-8"))
var request = DetailSearchRequest()
request.siteId = siteId
request.language = Locale.getDefault().language // Getting system language
searchService.detailSearch(request, object: SearchResultListener<DetailSearchResponse>{
override fun onSearchError(searchStatus: SearchStatus?) {
Log.e("SITE_KIT","${searchStatus?.errorCode} - ${searchStatus?.errorMessage}")
}
override fun onSearchResult(detailSearchResponse: DetailSearchResponse?) {
var site = detailSearchResponse?.site
site?.let {
Log.i("SITE_KIT", "Name => ${it.name}," +
"Format address => ${it.formatAddress}, " +
"Coordinate => ${it.location.lat} - ${it.location.lng}, " +
"Phone => ${it.poi.phone}, " +
"Photo URLS => ${it.poi.photoUrls}, " +
"Rating => ${it.poi.rating}, " +
"Address Detail => ${it.address.thoroughfare}, ${it.address.subLocality}, " +
"${it.address.locality}, ${it.address.adminArea}, ${it.address.country}")
} ?: kotlin.run {
Log.e("SITE_KIT","Site Place couldn't find with the given site ID")
}
}
})
}
First, we need to create a SearchService object from the SearchServiceFactory class. For this, we can use the create() method of the SearchServiceFactory class. We need to declare two parameters in create() method.
The first of these parameters is context value. It is recommended that Context value should be in Activity type. Otherwise, when HMS Core(APK) needs to be updated, we can not receive any notification about it.
The second parameter is API Key value that we can access via AppGallery Connect. This value is generated automatically by AppGallery Connect when a new app is created. We need to encode API parameter as encodeURI.
After creating our SearchService object as I described above, we can create a DetailSearchRequest object. We will specify the necessary parameters on this object related to the place which we want want to get information.
After creating our DetailSearchRequest object, we can determine parameters for a place that we want to get information. Two parameters are specified here:
SiteId: There is a unique id value for each Site in Site Kit. This parameter is used to specify the id value of the place whose information is to be obtained.
Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, language of the query field we have specified in the query field is accepted by default. In example code snippet in above, language of device has been added automatically in order to get a healthy result.
After entering the id value and language parameter of the place that we want to learn in detail, we can start learning the details. For this, we will use detailSearch() method of the SearchService object. This method takes two parameters.
For the first parameter, we must specify DetailSearchRequest object we have defined above.
For the second parameter, we have to implement SearchResultListener interface. Since this interface has a generic structure, we need to specify class belonging to the values to be returned. We can get the incoming values by specifying DetailSearchResponse object. Two methods should be override with this interface. onSearchError() method is executed if operation fails, and onSearchResult() method is executed if operations is successful. There is one value in DetailSearchResponse. This value is Site object that belongs to the id value. With the Site variable of DetailSearchResponse object, we can access information belong to place we have searched.
sujith.e said:
Hi,Why API key is required?
Click to expand...
Click to collapse
API key is a simple credential for accessing Huawei services. Your API key is creating automatically on the AppGallery Connect when you create an application, and then your app can use the key to call public APIs provided by Huawei.
When an app calls a public API provided by Huawei, we should give this information to API to help Huawei to identify our application.

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

Beginner: Integration of Huawei Site Kit and Cloud DB in Android (Kotlin)

Introduction
In this article, we will be learning how to integrate the Huawei Site kit and Cloud DB integrations in Android using Kotlin. Using AGC Cloud DB service, Service Providers from multiple cities can manage their data through CRUD (Create, Read, Update and Delete) operations. Using Site Kit user can search nearby stores and check stores details.
Development Overview
You need to install Android Studio and I assume that you have prior knowledge about the Android and Kotlin
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later
Android studio installed.
HMS Core (APK) 4.x or later
Integration of Site Kit
Site Kit provides place search services including keyword search, nearby place search, place detail search, and place search suggestion, helping your app provide convenient place-related services to attract more users and improve user loyalty.
Step 1: To integrate Site kit, need to add the below library:
Code:
implementation 'com.huawei.hms:site:5.0.2.300’
Step 2: How to get API Key?
Create an app in AppGallery Connect enter all necessary information.
Generate and configure the signing certificate fingerprint.
Add the AppGallery Connect plug-in and the Maven repository in the project-level build.gradle file. Configure the signature file in Android Studio.
For details, refer to Preparations for Integrating HUAWEI HMS Core.
After configure project, you can find API key in below image.
{
"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"
}
Step 3: To initialize HMS Site kit:
searchService = SearchServiceFactory.create(this, Utils.getApiKey())
To fetch nearby stores based on user’s current location:
SearchServiceActivity.kt
Code:
intent.let {
val request = NearbySearchRequest().apply {
queryString=it.getStringExtra(AppConstants.REQUEST_QUERY).toString()
setQuery(queryString)
setLocation(
Coordinate(
it.getDoubleExtra(AppConstants.SERVICE_LAT_KEY, 0.0),
it.getDoubleExtra(AppConstants.SERVICE_LNG_KEY, 0.0)
)
)
}
imageString = it.getStringExtra(AppConstants.PROVIDER_IMAGE_KEY).toString()
searchService?.nearbySearch(request, searchResultListener)
}
Results
Note: For more details, refer Site kit integration procedure. Site kit- SDK integration
Integration of Cloud DB
In this scenario, we can learn about a database service that runs on a cloud and is accessible from anywhere. Find the following points for better understand:
How to use Cloud DB to develop applications?
How to read, write and query application data to Cloud DB?
This service provides the synergy database product that provides data synergy management capabilities between the device and the cloud, unified data models, and various data management APIs.
Cloud DB supplies us simply cloud database and our project work together successfully and we can take advantages of CRUD (Create, Read, Update and Delete) operations.
Prerequisites
To use the Cloud DB for build application service, you need to complete the following preparations:
You have registered an account on the AppGallery Connect console and passed real-name authentication.
You have created a project and application on the AppGallery Connect console.
You have enabled the Anonymous account authentication service for the application to use permissions of the authentication user.
You have installed Android Studio on the local host.
Enable Cloud DB Service
Before using the Cloud DB service, you need to enable it.
Log in to AppGallery Connect and click My Projects.
Select a project from the project list and click an app for which you need to enable the Cloud DB service.
In the navigation bar, choose Build > Cloud DB.
Click Enable now to enable the Cloud DB service.
Select the Data storage location.
After the service is initialized, the Cloud DB service is enabled successfully.
After the service is initialized, the Cloud DB service is enabled successfully.
Adding and Exporting Object Types
The following example shows how to create object types on the AppGallery Connect console and export the object type file in the Java format for Android application development.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add an object type.
3. In the navigation bar, choose Build > Cloud DB.
4. Click Add to navigate to the object type creation page.
5. Set Object Type Name to LoginInfo, and click Next.
6. Click “+Add Field”, add the fields as per your requirements and click Next.
7. (Optional) Click “+Add Index”.
8. Add permissions as follows and click Next. (For Everyone, upsert and delete access is not allowed).
9. Click OK. Object types are created and displayed in the object type list.
The created object types are displayed in the object type list.
Repeat the above steps to create to create multiple table.
10. Click “Export” button
11. Set the format of the file to be exported to JAVA.
12. Set the Java file type to Android.
13. Enter the package name in the JAVA file.
The package name can contain only the following three types:
Letters: A–Z or a–z, which are mandatory
Digits: 0–9
Special characters: underscore (_) and period (.)
15. Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project. The file that contains all object types in the version is exported to the local PC. The exported Java file will be added to the local development environment in subsequent steps.
Cloud DB Zone
You can create a Cloud DB zone on the AppGallery Connect console. Perform the following steps to set Cloud DB Zone Name.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add a Cloud DB zone.
3. In the navigation tree, choose Build > Cloud DB.
4. Click the Cloud DB Zones tab.
5. Click Add to go to the Cloud DB zone creation page.
6. Enter Your App Name in the Cloud DB Zone Name text box.
7. Click OK the created Cloud DB zones are displayed in the Cloud DB zone list.
Configuring the Development Environment
Add a Cloud DB SDK to the dependencies node in the build.gradle file in the Project/app directory.
Code:
implementation <strong>'com.huawei.agconnect:agconnect=database:1.2.3.301’</strong>
In the build.gradle file, set the compatibility mode of Java source code to JDK1.8.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
Adding Object Type Files
During application development, you can directly add the JAVA files exported from the AppGallery Connect console to the local development environment, and use the createObjectType() method in the AGConnectCloudDB class to define and create object types. Then you do not need to create object types for local application development.
Add all exported files to the local development environment.
Initialize Cloud DB. Use the createObjectType() method in the AGConnectCloudDB class to define and create object types.
Initializing
After adding an object type file, you can use the Cloud DB to develop an application. When developing an application, you need to initialize AGConnectCloudDB, and create Cloud DB zone and object types.
Initialize AGConnectCloudDB in an application’s CloudDBZoneWrapper
Code:
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
Obtain the AGConnectCloudDB instance and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance();
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
Create the Cloud DB zone configuration object and open the Cloud DB zone. Add the below code in CloudDBZoneWrapper class.
Code:
public void openCloudDBZoneV2() {
mConfig = new CloudDBZoneConfig(AppConstants.URBAN_HOME_SERVICES,
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
Log.w(TAG, "open clouddbzone success");
mCloudDBZone = cloudDBZone;
// Add subscription after opening cloudDBZone success
mUiCallBack.onInitCloud();
addSubscription();
}).addOnFailureListener(e ->
Log.w(TAG, "open clouddbzone failed for”));
}
Writing Data
You can use the executeUpsert() API to write one object or a group of objects to the current Cloud DB zone.
Add the below code in CloudDBZoneWrapper class.
Code:
public void insertDbZoneInfo(T objectInfo) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> upsertTask = mCloudDBZone.executeUpsert(objectInfo);
upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
mUiCallBack.onInsertSuccess(cloudDBZoneResult);
}).addOnFailureListener(e -> {
mUiCallBack.updateUiOnError("Insert table info failed");
});
}
Viewing Data
Data added on the application page will be stored on the cloud. After a listener for data changes is registered on the device, the device will be notified when there is any changes on the cloud, and the local data will be updated in time.
You can use the query condition together with the subscribeSnapshot() method to specify an object to be listened on. When the data of the object is changed, the device will be notified and the original data stored on the cloud will be synchronized to the device based on the data changes information obtained by snapshots.
Add the below code in CloudDBZoneWrapper class.
Code:
private OnSnapshotListener<T> mSnapshotListener = (cloudDBZoneSnapshot, e) -> {
if (e != null) {
Log.w(TAG, "onSnapshot" );
return;
}
CloudDBZoneObjectList<T> snapshotObjects = cloudDBZoneSnapshot.getSnapshotObjects();
List<T> dbZoneList = new ArrayList<>();
try {
if (snapshotObjects != null) {
while (snapshotObjects.hasNext()) {
T objectInfo = snapshotObjects.next();
dbZoneList.add(objectInfo);
}
}
mUiCallBack.onSubscribe(dbZoneList);
} catch (AGConnectCloudDBException snapshotException) {
Log.w(TAG, "onSnapshot:(getObject)");
} finally {
cloudDBZoneSnapshot.release();
}
};
Querying Data
The executeQuery(), addOnSuccessListener(), and addOnFailureListener() methods are used together to query data in asynchronous mode.
Add the below code in CloudDBZoneWrapper class.
Code:
public void queryAllData(CloudDBZoneQuery<T> query) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<CloudDBZoneSnapshot<T>> queryTask = mCloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<T>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<T> snapshot) {
processQueryResult(snapshot);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
mUiCallBack.updateUiOnError("Query failed");
}
});
}
Deleting Data
You can use the executeDelete() method to delete a single object or a group of objects. When deleting data, Cloud DB will delete the corresponding data based on the input object primary key and does not check whether other attributes of the object are consistent with the stored data. When a group of objects are deleted, the deletion operation is atomic. That is, objects in the list are either all deleted successfully or all fail to be deleted.
Add the below code in CloudDBZoneWrapper class.
Code:
public void deleteTableData(List<T> tableObject) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> deleteTask = mCloudDBZone.executeDelete(tableObject);
if (deleteTask.getException() != null) {
mUiCallBack.updateUiOnError("Delete service type table failed");
return;
}
mUiCallBack.onDelete(tableObject);
}
}
Editing Data
You can use the editService() method to edit professional’s details.
Add the below code in ManageServiceActivity.kt class.
Code:
override fun editService(listObject: ServiceType) {
val intent = Intent(this, AddServiceActivity::class.java)
intent.apply {
putExtra(AppConstants.CATEGORY_NAME, listObject.cat_name)
putExtra(AppConstants.PROVIDER_PH_NUM, listObject.phone_number.toString())
putExtra(AppConstants.PROVIDER_MAIL_ID, listObject.email_id)
putExtra(AppConstants.PROVIDER_COUNTRY, listObject.country)
putExtra(AppConstants.PROVIDER_ID, listObject.id)
putExtra(AppConstants.PROVIDER_NAME, listObject.service_provider_name)
putExtra(AppConstants.PROVIDER_CITY, listObject.city)
putExtra(AppConstants.PROVIDER_STATE, listObject.state)
}
startActivity(intent)
}
Results
Tips and Tricks
Always use the latest version of the library.
Always provide proper Roles to user in Object Types.
Note: For more details, please refer Cloud Db service integration documentation, Cloud DB- Introduction
Conclusion
By using Cloud DB you can connect with Database without the need of APIs. You can perform the CRUD operations and also can restrict user access for the tables. Easy to connect with the application. Also you can search nearby service (plumber, electrician, painter etc) using site kit like as etc.
Site Kit to fetch nearby stores.
Cloud DB service to add, delete and edit professional’s details.
References
Site Kit
Cloud DB- Applying for Cloud BD
Cloud DB- Introduction
Checkout in forum

Beginner: Integration of Huawei InAppMessage feature for promoting products in E-commerce app (React Native)

Overview
You can use App Messaging of AppGallery Connect to send relevant messages to target active users of your app to encourage them to use key app functions, or send attractive promotion activities to enhance user loyalty. App Messaging even allows you to customize your messages look and the way they will be sent, in addition to default message layouts. You can also define events for triggering message sending to your users at the right moment.
{
"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"
}
In this article, I will show how user can promote their products using InAppMesseage service.
App Messaging allows you to send targeted messages based on user behaviour in your app to engage users and encourage certain user activities such as update, browse, subscribe and purchase. For example, you can use this service to send a promotion message of a product. When a user views product information, improving the sales and purchase rate.
Create Project in Huawei Developer Console
Before you start developing an app, configure app information in App Gallery Connect.
Register as a Developer
Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, refer to Registration and Verification.
Create an App
Follow the instructions to create an app Creating an App Gallery Connect Project and Adding an App to the Project. Set the data storage location to Germany.
React Native setup
Requirements
Huawei phone with HMS 4.0.0.300 or later.
React Native environment with Android Studio, NodeJs and Visual Studio code.
Dependencies
Gradle Version: 6.3
Gradle Plugin Version: 3.5.2
React Native CLI: 2.0.1
1. Environment set up, refer link.
2. Create project using below command.
Code:
react-native init project name
3. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
Generating a Signing Certificate Fingerprint
Signing certificate fingerprint is required to authenticate your app to Huawei Mobile Services. Make sure JDK is installed. To create one, navigate to JDK directory’s bin folder and open a terminal in this directory. Execute the following command:
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
This command creates the keystore file in application_project_dir/android/app
The next step is to obtain the SHA256 key which is needed for authenticating your app to Huawei services, for the key store file. To obtain it, enter following command in terminal:
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
After an authentication, the SHA256 key will be revealed as shown below.
Adding SHA256 Key to the Huawei project in App Gallery.
Copy the SHA256 key and visit AppGalleryConnect/ <your_AppMessage_project>/General Information. Paste it to the field SHA-256 certificate fingerprint.
Download the agconnect-services.json from App Gallery and place the file in android/app directory from your React Native Project.
Follow the steps to integrate the InAppMessage plugin to your React Native Application.
Enable the AppMessaging and Analytics kit from ManageAPIs as below.
Integrate the Hms-InAppMessage plugin:
User have react native version 16.6.0 install below command
Code:
npm install @react-native-agconnect/[email protected]
User have react native version 17.0.0 install below command
Code:
npm install --legacy-peer-deps @react-native-agconnect/appmessaging
Download the Plugin from the Download Link
Download ReactNative InAppMessage Plugin under node_modules/@react-native-agconnect of your React Native project, as shown in the directory tree below:
Code:
project-dir
|_ node_modules
|_ ...
|_ @react-native-agconnect
|_ ...
|_ appmessaging
|_ ...
|_ ...
Navigate to android/app/build.gradle directory in your React Native project. Follow the steps:
Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.4.1.300’)
Android setup:
Step 1: An example of your AndroidManifest.xml as follows:
Code:
<activity
android:name="com.huawei.agc.rn.appmessaging.example.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Step 2: Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Code:
defaultConfig {
applicationId "<package_name>"
minSdkVersion 19
/*
* <Other configurations>
*/
}
Creating an In-App Message​To send huawei in-app messages to users in specific scenarios, you need to create them in AppGallery Connect first and set the message layout and sending target
Procedure​1. Sign in to AppGallery Connect and click My projects.
2. Find and click your project.
3. Navigate to Grow > App Messaging and click New.
4. Set Name and Description
5. Set the layout and content and click Next.
Select the message type from the Type drop-down list box. Currently, the following options are supported: Pop-up, Image, and Banner.
6. Set the sending time and click Next.
7. Set conversion events.
Associate the display or tap of the in-app message with a conversion event. The conversion relationship will be displayed in statistics.
8. Click Save and Publish in the upper right corner to complete message creation.
In-App Message Display​The prerequisites for the React Native App Messaging plug-in to display in-app messages as follows:
1. The app must be running on the foreground.
2. A user triggers the event upon which an in-app message will be displayed. Then the React Native App Messaging plug-in synchronizes the message data from the AppGallery Connect server or obtains the message data from the local cache and determines whether to display the message.
Add Below Code in App.js:
The AGCAppMessaging.setFetchMessageEnable API can be called to enable or disable data synchronization from the AppGallery Connect server.
Code:
setFetchMessageEnable() {
AGCAppMessaging.getInstance().setFetchMessageEnable(true).then(result => {
Alert.alert("[setFetchMessageEnable] " + JSON.stringify(result));
this.createCustomView("setFetchMessageEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setFetchMessageEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setFetchMessageEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
The AGCAppMessaging.setDisplayEnable API can be called to set whether to enable message display.
Code:
setDisplayEnable() {
AGCAppMessaging.getInstance().setDisplayEnable(false).then(result => {
Alert.alert("[setDisplayEnable] " + JSON.stringify(result));
this.createCustomView("setDisplayEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setDisplayEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setDisplayEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
To add a custom view on the Android platform, add the following code to the onCreate method of your React-Native project /Android/MainApplication.java.
Code:
AgcAppMessagingModule.addCustomView();
Call the AGCAppMessaging.handleCustomViewMessageEvent for custom app message interactions. The following example calls the AGCAppMessaging.ON_MESSAGE_DISPLAY event once the custom app message has been shown:
Code:
componentDidMount() {
this.addMessageCustomViewListener();
}
addMessageCustomViewListener = () => {
AGCAppMessaging.getInstance().addMessageCustomViewListener((result) => {
Alert.alert(AGCAppMessaging.EventTypes.CUSTOM_VIEW + JSON.stringify(result))
/*
* Add Custom Message Event Handler method.
* When using custom app message layout, handle custom app message click events like below.
* gets eventType ( AGCAppMessaging.ON_MESSAGE_DISPLAY, AGCAppMessaging.ON_MESSAGE_CLICK, AGCAppMessaging.ON_MESSAGE_DISMISS, AGCAppMessaging.ON_MESSAGE_ERROR)
* and dismissType param( AGCAppMessaging.DISMISS_TYPE_CLICK, AGCAppMessaging.DISMISS_TYPE_CLICK_OUTSIDE, AGCAppMessaging.DISMISS_TYPE_AUTO, AGCAppMessaging.DISMISS_TYPE_SWIPE) when using AGCAppMessaging.ON_MESSAGE_DISMISS.
*/
this.handleCustomViewMessageEvent();
});
handleCustomViewMessageEvent() {
const customMessageDisplayReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISPLAY
}
const customMessageClickReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_CLICK
}
const customMessageDismissReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISMISS,
"dismissType": AGCAppMessaging.DismissTypes.DISMISS_TYPE_CLICK
}
const customMessageErrorReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_ERROR
}
AGCAppMessaging.getInstance().handleCustomViewMessageEvent(customMessageDisplayReq).then(result => {
Alert.alert("[handleCustomViewMessageEvent] " + JSON.stringify(result));
this.createCustomView("handleCustomViewMessageEvent : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[handleCustomViewMessageEvent] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[handleCustomViewMessageEvent] Error/Exception: ", JSON.stringify(err) + "")
});
}
class AGCAppMessaging{
constructor() {
this.emitter = new NativeEventEmitter(AGCAppMessagingModule);
}
static getInstance() {
if (!this.instance) {
this.instance = new AGCAppMessaging();
}
return this.instance;
}
addMessageDisplayListener(listener){
return subscription = this.emitter.addListener(
EventTypes.ON_MESSAGE_DISPLAY, listener
);
}
Test InAppMessage
Huawei In-app messages can only be displayed to users who have installed your officially released app. App Messaging allows you to test an in-app message when your app is still under tests. The testing procedure is as follows:
1. Obtain the anonymous application identifier (AAID) of the test device. For details, refer to Obtaining AAID.
2. Sign in to AppGallery Connect and select My projects.
3. Find your project from the project list and click the app for which you want to test an in-app message on the project card.
4. Navigate to Growing > App Messaging > Management, find the message that you need to test, and click Test in the Operation column.
5. Click Add test user and enter the AAID of the test device in the text box.
6. Click Save to set the in-app message to a test message and save the device as a test device.
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt.
2. Navigate to android directory and run the below command for signing the Apk.
Code:
gradlew assembleRelease
Output:
        
Tips and Tricks
Download latest HMS ReactNativeAppMessage plugin.
Add AAID to Test AppMessage in AppGalleryConnect.
For project cleaning, navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion:
In this article, we have learnt to integrate InAppMessage in React native project. We can integrate this service in different scenarios such as Travel, Education, Finance, Gaming and E-commerce apps to send the update, browse, subscribe and promote the product for better sales.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference:
App Messaging
Original Source

Categories

Resources