HUAWEI Analytics Kit: Data Export - Huawei Developers

Use Cases
HUAWEI Analytics Kit provides a server API for you to export event data collected on devices and import the data to your BI system for unified data analysis. After the export is complete, Analytics Kit asynchronously uploads the exported data to the Object Storage Service (OBS) and then returns the export result and data storage path to your app server by sending an HTTPS POST request to call its callback API. To ensure data security, the download link will become invalid after 2 hours.
The following table describes the export states that are currently supported.
{
"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 following table lists the data filter criteria.
Getting Started
Setting the Callback API
Sign in to AppGallery Connect. Go to My projects > HUAWEI Analytics > Management > Analysis setting, and select Set Callback API to set related parameters.
1. Configure the callback API URL for receiving the data download link.
2. Configure the HTTPS certificate.
3. Click Test callback to test the function of the callback API. After the test is successful, click Submit to complete the callback API configuration.
Development Guide
Before developing a callback API, you need to prepare a public network domain name and an API that can receive POST requests. Ensure that the POST API has an HTTPS certificate.
The development procedure is as follows:
1. Develop the callback API. In the sample code, the domain name is habackup.hwcloudtest.cn, which is accessible by your server.
Code:
@RequestMapping(value = "/agc/analytics/callback", method = RequestMethod.POST)
public ResultResp callback(@RequestBody @Valid ExportDataCallbackReq req) {
ResultResp result = new ResultResp();
// Receive the callback after the export task is generated.
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("the download url: {}", req.getFilePath());
}
// Obtain the download link to continue.
result.setResultCode("0");
result.setResultMsg("success");
return result;
}
Requested object:
Code:
public class ExportDataCallbackReq implements Serializable {
private static final long serialVersionUID = -8014011591749838257L;
@JsonProperty("request_id")
private String requestId;
@JsonProperty("app_id")
private String appId;
@JsonProperty("status")
private String status;
@JsonProperty("file_path")
private String filePath;
@JsonProperty("status_time")
private String statusTime;
}
2. Go to HUAWEI Analytics > Management > Analysis setting to configure the callback API.
3. Call the public API to obtain the token
POST request:
URI: https://oauth-login.cloud.huawei.com/oauth2/v2/token
Header:
Code:
Content-Type:Application/x-www-form-urlencoded
Body:
Code:
grant_type:client_credentials
client_id:100664247
client_secret:170e4ecb457bd73fa7c977de976274a7
Response:
Code:
{
"access_token": "CV6qeoJReXe+YfDRQomDe9VW1B6fzIH1QU260T94x4RBLUSZRjTRIcY7IngF1cPIEYaPhJCjVNOxrhvAo49Ay/Ukkf+p",
"expires_in": 3600,
"token_type": "Bearer"
}
4. Start data export.
POST request:
URI: https://datacollector-drcn.dt.hicloud.com/analytics/export/raw_data_requests/v2
Header:
Code:
Authorization:Bearer CV6qeoJReXe+YfDRQomDe9VW1B6fzIH1QU260T94x4RBLUSZRjTRIcY7IngF1cPIEYaPhJCjVNOxrhvAo49Ay\/Ukkf+p (token_type + space + access_token, obtained from the token response)
x-App-id:10066424
Content-Type:Application/json
x-product-id:9105163812218569643
Body:
Code:
{
"date_range": {
"start_date": "2020-2-29",
"end_date": "2020-3-10"
},
"file_format": "csv",
"filters": []
}
Response:
Code:
{
"result_code": "0",
"result_msg": "success"
}
5. View the export status.
Go to My projects > HUAWEI Analytics > Management > Data export.
6. After the export is complete, the Analytics Kit automatically calls the callback API to obtain the export result. Obtain the download link from the file_path field. The link is effective in 6 hours.
7. View the export result. If the following information is displayed, the export is successful.
Code:
[
{
"request_id": "c0b41debe8064c54ab200d30907f40c5",
"App_id": "100664247",
"status": "EXPORTED",
"file_path": "https://nsp-ha-gdpr-drcn.obs.cn-north-2.myhuaweicloud.com/20200430_14_c0b41debe8064c54ab200d30907f40c5.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=F9WBKUUWDQODJO4FQMBF%2F20200430%2Fcn-north-2%2Fs3%2Faws4_request&X-Amz-Date=20200430T073623Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=9145e80d51e21cd295861a5a0688bbcfbf8805e071cd8b98e08b5eacf2171fdb",
"status_time": "2020-04-30 07:37:02"
}
]
For details about the fields int he exported file, please refer to Description of Fields in the Export Data File.

Related

Accessing HUAWEI Analytics Kit

HUAWEI Analytics Kit is based on the event analytics data model.
The analytics data model uses the Event-Param-User model to record data, describes events using parameters, and describes the characteristics of users.
{
"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"
}
HUAWEI Analytics Kit collects the AAID that is allocated by the HMS Instance ID to each app instance installed on the device. The AAID is used for connecting various HMS Core services, such as HUAWEI Push Kit, HUAWEI Analytics Kit, and Remote Configuration.
The AAID will be reset in the following scenarios:
The user uninstalls or reinstalls the app.
The user restores the device to its factory settings.
The user clears the app data.
The app calls the clearCachedData API.
Procedure
1. Initialize the HMS Core Analytics SDK by calling the getInstance API.
Code:
HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
2. Record defined events using the onEvent API. For definitions of the events, please refer to Event Description.
3. Call APIs of HUAWEI Analytics Kit to implement the corresponding functions. For details, please refer to API Reference. For example, call the setUserProfile API to set user attributes.
Sample Code
1. After the agconnect-services.json file is imported successfully, initialize HUAWEI Analytics Kit in the onCreate method of the first activity to obtain a HiAnalyticsInstance instance. If the agconnect-services.json file is incorrect, data cannot be collected at specified trigger points.
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Enable SDK log recording.
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance = HiAnalytics.getInstance(this);
// Or use the context for initialization.
// Context context = this.getApplicationContext();
// HiAnalyticsInstance instance = HiAnalytics.getInstance(context);
// instance.setUserProfile("userKey","value");
}
2. Insert trigger points in proper positions of the code.
Code:
//Customize trigger points and add trigger points in the proper position of the code.
Bundle bundle = new Bundle();
bundle.putString("exam_difficulty","high");
bundle.putString("exam_level","1-1");
bundle.putString("exam_time","20190520-08");
instance.onEvent("begin_examination", bundle);
//Add trigger points for predefined events.
Bundle bundle_pre = new Bundle();
bundle_pre.putString(PRODUCTID, "item_ID");
bundle_pre.putString(PRODUCTNAME, "name");
bundle_pre.putString(CATEGORY, "category");
bundle_pre.putLong(QUANTITY, 100L);
bundle_pre.putDouble(PRICE, 10.01);
bundle_pre.putDouble(REVENUE, 10);
bundle_pre.putString(CURRNAME, "currency");
bundle_pre.putString(PLACEID, "location_ID");
instance.onEvent(ADDPRODUCT2WISHLIST, bundle_pre);
Using the Debug Mode
During the development, you can enable the debug mode to view the event records in real time, observe the results, and adjust the event tracing scheme.
Enabling/Disabling the Debug Mode
Run the following command on an Android device to enable the debug mode:
Code:
adb shell setprop debug.huawei.hms.analytics.app package_name
After the debug mode is enabled, all events will be reported in real time.
Run the following command to disable the debug mode:
Code:
adb shell setprop debug.huawei.hms.analytics.app .none.
You can go to HUAWEI Analytics > Management > App Debugging to view the reported data, as shown in the following figure.
For details about how to view the analysis data, please refer to App Debugging.

Great way to test android apps[HMS and GMS], A/B Testing

More information about this, you can visit HUAWEI Developer Forum
​Introduction
This article will guide you to use A/B testing in android project. It will provide details to use HMS and GMS.
Steps
1. Create App in Android
2. Configure App in AGC
3. Integrate the SDK in our new Android project
4. Integrate the dependencies
5. Sync project
Procedure
Step1: Create application in android studio.
HMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.3.1.300'
apply plugin:'com.huawei.agconnect'
Add below dependencies in root directory
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
GMS related dependencies, Add below dependencies in app directory
Code:
implementation 'com.google.android.gms:play-services-analytics:17.0.0'
implementation 'com.google.firebase:firebase-config:19.2.0'
Add below dependencies into root directory
Code:
classpath 'com.google.gms:google-services:4.3.3'
Step2: Create MobileCheckService class, using this class you can identify whether the device has HMS or GMS.
Code:
class MobileCheckService {
fun isGMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
if (com.google.android.gms.common.ConnectionResult.SUCCESS === result) {
return true
}
}
return false
}
fun isHMSAvailable(context: Context?): Boolean {
if (null != context) {
val result: Int = HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
if (com.huawei.hms.api.ConnectionResult.SUCCESS == result) {
return true
}
}
return false
}
}
Step3: Create instance for Mobilecheckservice inside activity class. Inside OnCreate() call checkAvailableMobileService().This method return whether the device has HMS or GMS.
Code:
private fun checkAvailableMobileService() {
if (mCheckService.isHMSAvailable(this)) {
Toast.makeText(baseContext, "HMS Mobile", Toast.LENGTH_LONG).show()
configHmsTest()
} else
if (mCheckService.isGMSAvailable(this)) {
Toast.makeText(baseContext, "GMS Mobile", Toast.LENGTH_LONG).show()
configGmsTest()
} else {
Toast.makeText(baseContext, "NO Service", Toast.LENGTH_LONG).show()
}
}
Step4: If the device support HMS, then use AGConnectConfig.
Code:
private fun configHmsTest() {
val config = AGConnectConfig.getInstance()
config.applyDefault(R.xml.remote_config_defaults)
config.clearAll()
config.fetch().addOnSuccessListener { configValues ->
config.apply(configValues)
config.mergedAll
var sampleTest = config.getValueAsString("Festive_coupon")
Toast.makeText(baseContext, sampleTest, Toast.LENGTH_LONG).show()
}.addOnFailureListener { Toast.makeText(baseContext, "Fetch Fail", Toast.LENGTH_LONG).show() }
}
Step5: If the device support GMS, then use FirebaseRemoteConfig.
Code:
private fun configGmsTest() {
val firebase = FirebaseRemoteConfig.getInstance();
val configSettings = FirebaseRemoteConfigSettings.Builder().build()
firebase.setConfigSettingsAsync(configSettings)
firebase.setDefaultsAsync(R.xml.remote_config_defaults)
firebase.fetch().addOnCompleteListener { configValues ->
if (configValues.isSuccessful) {
firebase.fetchAndActivate()
var name = firebase.getString("Festive_coupon")
Toast.makeText(baseContext, name, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(baseContext, "Failed", Toast.LENGTH_LONG).show()
}
}
}
App Configuration in Firebase:
Note: A/B test is using HMS configuration, refer
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248355275100167&fid=0101187876626530001
Step1: To configure app into firebase Open firebase https://console.firebase.google.com/u/0/?pli=1
{
"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"
}
Step2: Click Add Project and add required information like App Name, package name, SHA-1.
Step3: After configuration is successful, then click A/B Testing in Grow menu.
To Start A/b testing experiment Click Create experiment button, It will show you list of supported experiments. Using Firebase you can do three experiments.
· Notifications
· Remote Config
· In-App Messaging
Notification: This experiment will use for sending messages to engage the right users at the right moment.
Remote Config: This experiment will use to change app-behavior dynamically and also using server-side configuration parameters.
In-App Messaging: This experiment will use to send different In-App Messages.
Step4: Choose AbTesting > Remote Config > Create a Remote Config experiment, provide the required information to test, as follows
Step5: Choose AbTesting > Remote Config > App_Behaviour, following page will display.
Step6: Click Start experiment, then start A/B test based on the experiment conditions it will trigger
Step7: After successful completion of experiment, we can get report.
Conclusion:
Using A/B test, you can control the entire experiment from HMS or GMS dashboard, this form of testing will be highly effective for the developers.
Reference:
To know more about firebase console, follow the URL https://firebase.google.com/docs/ab-testing
Share your thoughts on this article, if you are already worked with A/B tests, then you can share your experience on separation between them with us

Implementing SMS Verification with Huawei SMS Retriever

Hi everyone! Today I will briefly walkthrough you about how to implement an SMS Retriever system using Huawei’s SMSRetriever service.
{
"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"
}
First of all, let’s start with why do we need this service in our apps. Applications that involve user verification usually do this with an SMS code, and this SMS code is entered to a field in the app to verify user account. These sms codes are named as One-Time-Password, OTP for short. OTP’s can be used for verification of real user or increasing account security. Our purpose here is to retrieve this code and automatically enter it to the necessary field in our app. So let’s begin!
Our steps through the guide will be as:
Complete HMS Service implementation
1 — Require SMS read permission
2 — Initiate ReadSmsManager
3 — Register broadcast receiver for SMS
4 — Send SMS for user
5 — Register broadcast receiver for OTP — to extract code from SMS —
6 — Create SMSBroadcastReceiver class
1 — We begin by adding our required permission to the AndroidManifest.xml
XML:
<uses-permission android:name="android.permission.SEND_SMS" />
Note: Don’t forget to check if user has given permission.
Code:
val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
// Send sms
else
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.SEND_SMS), SEND_SMS_REQUEST_CODE)
2 — Then we add the ReadSmsManager to initiate our SMS service.
Before ReadSmsManager code snippet, we have to add Huawei Account Kit implementation.
Code:
implementation 'com.huawei.hms:hwid:5.1.0.301'
After Gradle sync, we can add the SMS manager to our class.
Code:
val task = ReadSmsManager.startConsent([email protected], mobileNumber)
task.addOnCompleteListener {
if (task.isSuccessful) {
Toast.makeText(this, "Verification code sent successfully", Toast.LENGTH_LONG).show()
} else
Toast.makeText(this, "Task failed.", Toast.LENGTH_LONG).show()
}
3 — For SMS broadcast receiver, we need to add this little code block.
Code:
val intentFilter = IntentFilter(READ_SMS_BROADCAST_ACTION)
registerReceiver(SmsBroadcastReceiver(), intentFilter)
Note: After you add this code block, you will get an error saying SmsBroadcastReceiver cannot be found, because we didn’t define it yet. We are just getting our SmsActivity ready. We will be adding it once we are done here.
4 — After we register our receiver, we can send the SMS to our user.
Code:
val smsManager = SmsManager.getDefault()
smsManager.sendTextMessage(
mobileNumber,
null,
"Your verification code is $otp",
null,
null
)
Note: here otp will cause an error as it is not defined anywhere yet. You should implement a random OTP generator fitting your likings and assign the value to otp .
5 — Now that we sent an SMS to user, we should register the broadcast receiver to be able to retrieve the code from it.
Code:
val filter = IntentFilter()
filter.addAction("service.to.activity.transfer")
val otpReceiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
intent.getStringExtra("sms")?.let { data ->
// You should find your otp code here in `data`
}
}
}
registerReceiver(otpReceiver, filter)
Note: Once we complete our classes, you should be setting your otp value to your view. This part is left out in the code snippet as view bindings and data bindings may vary on projects.
6 —Finally, where we get to read the messages and find our code.
Code:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.huawei.hms.common.api.CommonStatusCodes
import com.huawei.hms.support.api.client.Status
import com.huawei.hms.support.sms.common.ReadSmsConstant
class SmsBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val bundle = intent!!.extras
if (bundle != null) {
val status: Status? = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS)
if (status?.statusCode == CommonStatusCodes.TIMEOUT) {
// Process system timeout
} else if (status?.statusCode == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)?.let {
val local = Intent()
local.action = "service.to.activity.transfer"
local.putExtra("sms", it)
context!!.sendBroadcast(local)
}
}
}
}
}
}
So that’s it. You should be able to successfully register for SMS sending and retrieving, then read OTP from content and use in whatever way you like.
Thanks for reading through the guide and I hope it is simple and useful for you. Let me know if you have any suggestions or problems.
References
https://developer.huawei.com/consum...upport-sms-readsmsmanager-0000001050050553-V5
https://developer.huawei.com/consum...Guides/authotize-to-read-sms-0000001061481826
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98

How Can I Quickly Integrate Remote Configuration to a Web App?

Recently, I found that Remote Configuration of AppGallery Connect now supports the web platform, which I’ve long been waiting for. Previously, it has only been supported on Android, but now it can be applied to web apps. For details about the integration demo, visit GitHub.​
Integration Steps​1. Enable the service.
a) Sign in to AppGallery Connect and create a web app.
b) Enable Remote Configuration.
c) Click New parameter and set parameters.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2. Integrate the SDK.
a) Run the following command:
Code:
npm install –save @agconnect/remoteconfig
3. Implement the functions.
a) Obtain the local configuration parameters.
Create a local configuration map in the Vue.
Apply the local settings.
JavaScript:
export function applyDefault(map) {
return agconnect.remoteConfig().applyDefault(map);
}
b) Call the fetch API to fetch parameter values from the cloud.
JavaScript:
export async function fetch() {
return agconnect.remoteConfig().fetch().then(() => {
return Promise.resolve();
}).catch((err) => {
return Promise.reject(err);
});
}
c) Apply the parameter values to the local host immediately or upon the next launch.
1. Applying the parameter values immediately:
Call the apply API.
JavaScript:
export function apply() {
return agconnect
.remoteConfig().apply().then((res) => {
return Promise.resolve(res);
}
).catch(error => {
return Promise.reject(error);
});
}
2. Applying the parameter values upon the next launch:
Call the applyLastFetch API to apply the last fetched parameter values.
JavaScript:
// Load configurations.
export function applyLastLoad() {
return agconnect
.remoteConfig().loadLastFetched().then(async (res) => {
if (res) {
await agconnect.remoteConfig().apply(res);
}
return Promise.resolve(res);
}
).catch(error => {
return Promise.reject(error);
});
}
d) Obtain all parameter values from the local host and cloud.
Call the getMergedAll API to obtain all parameter values.
JavaScript:
export function getMergedAll() {
return agconnect.remoteConfig().getMergedAll();
}
e) Call the clearAll API to clear all parameter values.
JavaScript:
export function clearAll() {
agconnect.remoteConfig().clearAll();
}
References:
Demo:
https://github.com/AppGalleryConnect/agc-demos/tree/main/Web/agc-romoteconfig-demo-javascript
Remote Configuration Development Guide:
https://developer.huawei.com/consum...-remoteconfig-web-getstarted-0000001056501223
Well explained, Using remote config can we change UI elements.
What is the basic use of Remote Config in web?
sujith.e said:
Well explained, Using remote config can we change UI elements.
Click to expand...
Click to collapse
yes, that is convenient for developers.
ask011 said:
What is the basic use of Remote Config in web?
Click to expand...
Click to collapse
You can flexibly modify the behavior and appearance of applications by changing cloud parameter values.

Using Huawei App Messaging in Flutter

Huawei AppGallery Connect’s App Messaging service allows you to send targeted, useful in-app messages to your users.
The look and content of messages are completely customisable, and there is a wide range of triggers and filters that can be used to decide who will receive a message and when.
Let's take a look today at how we can set this up to work within a flutter project.
As always we will start with a fresh project but of course, you can just as easily use this guide to build the service into an app you already have!
Installing the Flutter Environment​
Download the Flutter SDK.
Decompress the package to any directory.
Add the Flutter command file to the environment variable.
Download the Flutter and Dart plugins in Android Studio.
{
"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"
}
Enabling the Service and Creating a Flutter project​Sign in to AppGallery Connect, click My projects, click your project, go to Grow > App Messaging, and click Use now. For more information, please refer to App Messaging.
If you do not have an Android project, create one first.
After completing these steps, you can start creating an in-app message.
Click New in the upper right corner.
Set Name and Description
Set the style and content and click Next.
Select a message type from the Layout drop-down list, and set its style and content. Currently, the Modal, Image, and Banner message types are supported.
Set target users and click Next.
In App, select the name of the app package for which you need to publish the in-app message.
You can click New condition to add a condition for matching target users, which include app version, OS version, language, country/region, audience, and more. Among the types, User attributes are defined under HUAWEI Analytics > Management > User attributes, and Prediction is defined by creating prediction tasks under My projects > Grow > Prediction.
Set the message sending time
Message display is triggered by specific events. App Messaging supports two types of trigger events: preset events and HUAWEI Analytics events.
(Optional) Set conversion events. Before setting a conversion event, you need to toggle it on first, which can be done as follows:
Go to HUAWEI Analytics > Management > Events and toggle Mark as conversion event and Event switch on for the specified event. In addition to the events the SDK collects, you can also create a preset or custom event for event tracking and analysis.
Finally, Click Save or Publish.
Integrating the Service SDK​Add dependencies​Start by creating a Flutter project in Android Studio (or opening one).
Then add the agconnect-services.json file from your AppGallery project to the android/app directory
Within the project level build.gradle file make sure to include the huawei maven repo and add the agcp package as a dependency.
Code:
buildscript {
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath 'com.huawei.agconnect:agcp:1.6.2.300'
}
}
Next in your app level build.gradle apply the agconnect plugin as so:
Code:
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.huawei.agconnect'
Then in your pubspec.yaml file add the App Messaging SDK dependency.
Code:
dependencies:
flutter:
sdk: flutter
agconnect_appmessaging: ^1.2.0+300
Displaying an In-App Message​If you choose to display a message using the default message layout, the development process is totally coding-free.
By integrating the SDK as above you are all good to go, your creating message will be displayed as per its filters and triggers.
You can also call APIs provided by the service SDK to customize your in-app message.
Customising the Message Layout​Add the following code to onCreate in MainActivity,
Code:
AGCAppMessagingCustomEventStreamHandler.addCustomView();
so that the service SDK can listen to the corresponding event and apply the customized layout.
Code:
streamSubscriptionDisplay = agconnectAppmessaging.customEvent.listen((event) {
showDialog(context ,event.toString());
agconnectAppmessaging.handleCustomViewMessageEvent
(AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
});
Then the message is displayed in your app.
Code:
void _showDialog(BuildContext context, String content) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
key: Key("dialog"),
title: Text("Result"),
content: Text(content),
actions: <Widget>[
FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
Testing an In-App Message​App Messaging allows you to test an in-app message before it is published. You need to obtain the Anonymous Application Identifier (AAID) of your test device by adding the following code to your Android app module.
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
textView.setText(aaid);
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
Sign in to AppGallery Connect, go to Grow > App Messaging > Messages, find the message that you created, click and select Test in the Operation column.
Click Add test user and enter the AAID
Click Save. Check whether the test message is properly displayed on your test device

Categories

Resources