Optimize Conversion Rate Using A/B Testing - Huawei Developers

This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home​Experiment your ideas, make your changes in website/Applications, AB Testing analytics will help you find which experiment results better conversion rate optimization.
Introduction
A/B Testing (also known as Split Testing), A/B testing is a fantastic method for find out the best online advertisement and marketing strategies. designers are using it at this very moment to obtain valuable insight regarding visitor behavior and to improve applications or website conversion rate.
A/B testing involves sending half your users to one version of a page, and the other half to another, and watching the analytics to see which one is more effective in getting them to do what you want them to do (for example, sign up for a user account), this helps you make reach more audience.
Implementation Process
1. Enabling A/B Testing, Access dependent service
2. Create an experiment
3. Manage an experiment
Enabling A/B Testing
· Create sample application in android and configure into AGC.
· Enable Push service and Analytics
· Open AGC select sample project Growing->A/B testing Now enable A/B testing.
After enabling service, you will get options
· Create notifications experiment.
· Create remote configuration experiment.
Creating an Experiment
Create Remote Configuration Experiment
The best way to implement new feature or an updated user experience, based on user response you can implement features. follow below steps.
Click create remote configuration experiment you will get below screen
{
"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"
}
Open AGC -> select project->Growing->Remote Configuration enable service
Now open A/B Testing tab.
Declare name and description then click Next Button.
· In target user page, set filter conditions, select target user ratio.
· Click Conditions and select one of the following filter conditions.
Version: Select the version of the app.
Language: Select the language of the device
Country/Region: Select the country or region where the device is located.
Audience: Select the audience of HUAWEI Analytics Kit.
User attributes: Select the user attributes of HUAWEI Analytics Kit
After the setting is complete, click Next.
· Create Treatment & Control Groups
To add multiple parameters using new parameter option.
To add multiple treatment group using New treatment group option.
You can create customize parameter names.
· After filling all details done, click next button.
· Create Track Indicators
Select main and optional indicators, then save all details
· After saving all details you will get below screen.
· After experiment created you can follow below steps.
Test the experiment
Start the experiment
View the report
Increase the percentage of users who participate in the experiment.
Release the experiment
Test an Experiment
Before starting an experiment, you need to test individually.
· Generate AAID
· Using Add test user and add an AAID of a test user.
· Run your app on the test user device and ensure that the test user can receive information.
· Follow below step to generate AAID.
Code:
private fun getAAID() {
var inst = HmsInstanceId.getInstance(this)
val aaid = inst.id
txtAaid.text=aaid
Log.d("AAID", "getAAID success:$aaid")
}
Starting an experiment
· Click Start operation column and click OK
Viewing an Experiment Report
· You can view experiment reports in any state. The system also provides the following information for each indicator by default
· Increment: The system compares the indicator value of the treatment group with that of the control group to measure the improvement of the indicator.
· Other related indicators: For example, for Retention rate after 1 day, the system also provides data about Retained users.
Releasing an Experiment
· Click Release in the operation column
· Select treatment group set condition name.
· Click Go to Remote configuration button.it will redirect new page.
· If you want modify any parameter values. click operation choose Edit option to modify values, Click Save Button.
Let’s do Code
· Setting Default In-app Parameter Values
Code:
val config = AGConnectConfig.getInstance()
val map: MutableMap<String, Any> = HashMap()
map["test1"] = "test1"
map["test2"] = "true"
config.applyDefault(map)
· Fetching Parameter Values from Remote Configuration
· You can call the fetch API to obtain parameter values from Remote Configuration in asynchronous mode.
· After the API is successfully called, data of the ConfigValues type is returned from Remote Configuration.
· After obtaining parameter value updates, the app calls the apply() method
· Calling the fetch() method within an interval will obtain locally cached data instead of obtaining data from the cloud.
· We can customize the fetch interval
Loading Process
· Applying parameter values Immediately.
Code:
config.fetch()
.addOnSuccessListener { configValues ->
config.apply(configValues)
}
.addOnFailureListener { error ->
Log.d("TAG", error.message)
}
· Applying parameter values upon the next startup
You can fetch parameter values at any time, in this case latest parameter values can be applied without asynchronous waiting.
Code:
val last = config.loadLastFetched()
config.apply(last)
config.fetch()
.addOnSuccessListener {
}
.addOnFailureListener { error ->
Log.d("TAG", error.message)
}
}
Report
Conclusion:
A/B testing which was earlier used mostly on e-commerce portals and websites has now been introduced for Android apps as well. This form of testing was found to be highly effective for the developers.
So, that's how to implement an A/B Testing in your next app.
Any questions about this, you can try to acquire answers from HUAWEI Developer Forum.

Related

How to Analyse your user and Improve User Engagement

Notifications play a vital role in your app success. They give you a platform to reach out to your users, interact with them, give them updates, update the app data and much more.
While notification is an important part of the whole app development process, it somehow is typical to integrate as compared to the normal android apis. The reason? Well, while normal apis need configuration inside the app only, notifications need more than that — outside configuration like handling user tokens, and sending notifications using those tokens.
The main goal of this app is to be a sample of how to build an high quality Android application that uses the Architecture components, MVVM, RxJava,HMS PUSH Kit,HMS Analytics Kit etc. in Kotlin
What is Kotlin? The Java alternative explained
{
"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"
}
Kotlin is a general purpose, free, open source, statically typed “pragmatic” programming language initially designed for the JVM (Java Virtual Machine) and Android that combines object-oriented and functional programming features
Safety features in Kotlin
· Speaking of avoiding common errors, Kotlin was designed to eliminate the danger of null pointer references and streamline the handling of null values.
· It does this by making a null illegal for standard types, adding nullable types, and implementing shortcut notations to handle tests for null.
· To avoid the verbose grammar normally needed for null testing, Kotlin introduces a safe call, written ?.. For example, b?.length returns b.length if b is not null, and null otherwise. The type of this expression is Int?.
RxJava:
· RxJava has become the single most important skill for Android development.
· Most of you must have worked with it in some form, either in your own codebase or through other third party libraries, like Fast Android Networking and Retrofit
How does this Reactive Stream implement?
· Publisher: These interfaces(APIs) define the structure of RxJava.
Code:
interface Publisher<T> {
fun subscribe(s: Subscriber<in T?>?)
}
· Subscriber: A Subscriber exposes the following callback methods.
Code:
interface Subscriber<T> {
fun onSubscribe(s: Subscription?)
fun onNext(t: T)
fun onError(t: Throwable?)
fun onComplete()
}
· Subscription: When the Subscriber becomes ready to start handling events, it signals the Publisher through its Subscription
Code:
interface Subscription {
fun request(n: Long)
fun cancel()
}
Publishers
Let’s see how publishers are structured in RxJava. RxJava provides following types of event publishers:
· Flowable: A Publisher that emits 0..N elements, and then completes successfully or with an error.
· Observable: Similar to Flowables but without a backpressure strategy. They were introduced in RxJava 1.x.
· Single: It completes with a value successfully or an error.(doesn’t have onComplete callback, instead onSuccess(val)).
· Maybe: It completes with/without a value or completes with an error.
Completable: It just signals if it has completed successfully or with an error.
What is MVVM?
Model-View-ViewModel architecture consists of 3 parts.
· The View gets user’s actions and sends to the ViewModel, or listens live data stream from the ViewModel and provides to the users.
· The ViewModel gets user’s actions from the View or provides data to View.
· The Model abstracts the data source. View and ViewModel uses that on data stream.
LiveData:
· LiveData is one of the newly introduced architecture components. LiveData is an observable data holder.
· This allows the components in your app to be able to observe LiveData objects for changes without creating explicit and rigid dependency paths between them.
· This decouples completely the LiveData object producer from the LiveData object consumer.
ViewModel:
· ViewModel is also one of the newly introduced architecture components.
· Architecture components provide a new class called ViewModel, which is responsible for preparing the data for the UI/View.
· ViewModel gives you a good base class for your MVVM ViewModel layer since ViewModel (and its children AndroidViewModel)’s extending classes are automatically having their holding data retained during configuration changes.
· This means that after configuration changes, this ViewModel holded data is immediately available to the next activity or fragment instance.
Project Structure:
We will create packages by features. It will make your code more modular and manageable.
DataBinding:
· Android data binding allows for 1 or 2-way binding within the layout XML files of Android. This should be familiar to anyone who has done web based development with Angular or Ember, or C# WPF development.
· The most basic case is to add an on-click listener. This requires no registering of on click listeners in any of your application code, just some XML in the layout file and a function to be called in your ViewModel class
Code:
<?xml version="1.0" encoding="utf-8"?>
<layout >
<data>
<variable
name=" "
type=""/>
</data>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@{viewModel.getHourOfDay()}"
tools:text="14:00" />
</RelativeLayout>
</layout>
Weather Notification API:
The Weather Notifications API enables you to set weather-driven push notifications to applications. With predefined weather parameter threshold values, you are able to be informed of certain weather phenomena like when rain, strong winds or exceptional heat starts.
The following content will be the coding process.
If you are interested, check the full content by https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201235519702030082&fid=0101187876626530001
More information about HMS, you can visit https://forums.developer.huawei.com/forumPortal/en/home

Online Food ordering app ([email protected]) | App Messaging | Analytics kit | JAVA Part-4

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Online food ordering is process to deliver food from restaurants. In this article will do how to Integrate Analytics, App-Messaging in food applications.
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.
Analytics Module
Huawei Analytics will helps to understand how people using mobile application. Analytics model help you gain a deeper insight into your user, products and contents.
1. Collect and report custom events.
2. Set a maximum of 25 user attributes
3. Automate event collection and session calculation with predefined event ID’s and parameter.
Use Cases
1. Analyze user behaviour using both predefined and custom events.
2. Use audience building to tailor your marketing activity to your users’ behaviour and preferences.
3. Use dashboards and analytics to measure your marketing activity and identify areas to improve.
Function Restrictions
Device restrictions: The following automatically collected events of analytics kit depend on HMS Core (APK). Therefore, which are not supported on third-party devices where HMS Core is not installed including but not limited to Oppo, Vivo, Xiaomi, Samsung and Oneplus.
Event quantity restriction: Each app can analyze a maximum of 500 events.
Event parameter restrictions: You can define a maximum of 25 parameters for each event, and maximum of 100 event parameter for each app.
AGC Configuration
1. Create an app adding an app to the project.
2. Enable Analytics Choose My Projects> Huawei Analytics
{
"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"
}
3. Enable Analytics API Choose My Projects > Project settings > Manage APIs
Integration
Create Application in Android Studio.
App level gradle dependencies.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Gradle dependencies
Code:
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
1. Create Instance for HiAnalyticsInstance in the onCreate method
Code:
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance = HiAnalytics.getInstance(this);
2. Create method for report an event.
Code:
private void reportevent() {
Bundle bundle = new Bundle();
bundle.putString("Name", signInResult.getUser().getDisplayName());
mInstance.onEvent("SIGNIN", bundle);
}
Output
App Messaging Module
Huawei App messaging is one of the power full tool to promote information to audience. This will help when you are trying to get more attention to your application. We can target active users to encourage them to use this app.
App Messaging allows to customize your messages visuals and the way they will be sent, and define events for triggering message sending to your users at the right moment.
Message Types
1. Pop-up Message: Title, body and contain an image, and up to two buttons.
2. Banner Message: Message is displayed on top of the screen, containing a thumbnail and the message title and body. user can tap the banner to access specified page.
3. Image: It contains only image. An image message can be a poster well designed to promote an activity. User can tap the image to access the activity details.
AGC Configuration
1. Enable App Messaging Api Choose My Projects > Project settings > Manage APIs
2. Enable App Messaging Choose My Projects > Growing > App Messaging Click Enable Now.
3. Click New button and enter the required information.
4. Enter required details, and then click Next button.
5. In Select Sending Target node, click New condition for matching target users.
Select conditions in Select drop-down, and then click Next
6. In Set Sending Time node, select Started and Ended drop-downs.
Select required options in Trigger event and Frequency limit, and then click Next
7. Once all the required information filled, and then click Save button
8. Navigate to Operation tab, and then click Test option to perform the App Messaging publishing
Integration
Gradle dependencies
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
1. Generate AAID, this AAID will help you to sending App-Messages.
Code:
private void generateAAID(){
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(aaidResult -> Log.d("AAID", "getAAID success:" + aaidResult.getId() ))
.addOnFailureListener(e -> Log.d("AAID", "getAAID failure:" + e));
}
2. For displaying messages we need to call AGConnectAppMessaging Instance.
3. setFetchMessageEnable() To allow data synchronization from the app gallery connect server.
4. setDisplayEnable() To Enable message display.
5. setForceFetch() To specify that the in-app message data must be obtained from App Gallery connect server.
Code:
private void initializeInAppMessage(){
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
Result:
Conclusion
In this Article, I have explained how to integrate App Messaging and Analytics Kit on food application.
Reference:
Analytics kit:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050745149
App Messaging:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-appmessage-introduction

【DTM】Visual Event Tracking for Web Pages (One)

Event tracking is a technology for collecting and processing user behavior data or events, and is widely used for user behavior analysis and data processing. It helps product managers, operations personnel, and data analysts to precisely collect and analyze user behavior data, create user profiles, as well as analyze and optimize products. However, manual event tracking has high requirements in terms of technical skills, as well as requiring a huge workload and a long development period.
The visual event tracking function of Dynamic Tag Management (DTM) was created to deal with such issues. DTM provides multiple solutions for tracking visual events of web pages: common visual event tracking, tag template-based visual event tracking, and visual event tracking by HUAWEI Analytics.
This article will illustrate how to use common visual event tracking.
Prerequisites​1. You have created an AppGallery Connect account and signed in to it by visiting the following URL address, click here
2. You have created a web app and its DTM configuration.
3. You have created your website and integrated the DTM configuration script into it. To integrate the DTM configuration script, perform the following:
a. Click the Configuration tab and then View in the DTM portal.
b. Copy the code snippet below and paste it to the top of the <head> section of each web page to track, so that the code snippet takes effect in a timely manner.
{
"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"
}
Common Visual Event Tracking​A visual event can be used as the trigger condition for reporting events to multiple third-party analytics platforms. This is applicable to scenarios where visual events and parameters need to be adjusted flexibly.
1.1 Accessing the Visual Event Tracking Page​ 1. Click the Visual event tab in the DTM portal.
2. Click Start on the page displayed.
1.2 Adding Visual Events​ 1. On the Add visual event page displayed, click Add on the right.
2. Select Button or link under Select element for visual event addition. (This option is selected by default.)
3. Select the Detail button under HUAWEI Mate Series on the left page.
Click OK in the displayed dialog box asking you whether to select elements of the same type.
4. Configure visual event information.
a. Enter a visual event name.
b. Click the hand icon, select HUAWEI Mate Xs, and enter a parameter name to add a visual event parameter.
c. Set Triggered on to Specified pages, and add the URL rule URL Equals https://XXXXXX.XXX.
5. Click OK to save the visual event.
6. Click the
icon on the right of a visual event to expand it.
7. Click the
icon in the upper left corner to exit the visual event tracking page.
1.3 Adding a Tag​ 1. Click the Tag tab.
2. Select a tag extension template, and set Trigger condition to MateSeriesView.
3. Click OK.
4. Click Save.
1.4 Creating and Releasing a Version​ 1. Click Create on the Version tab page.
2. On the Create version page, enter a version name and description.
3. Select Create and release version.
4. Click OK.
1.5 Triggering a Visual Event​ 1. Refresh the tested website and download the latest DTM configuration.
Note: By default, the DTM JavaScript SDK downloads the latest DTM configuration to the cache every 15 minutes. To download the latest DTM configuration immediately, disable the browser cache and refresh the tested website again.
2. Click any Detail button under HUAWEI Mate Series.
3. View reported data on the specified third-party analytics platform.
To learn more about DTM, click here.
For more details, you can go to:
Reddit to join our developer discussion
GitHub to download demos and sample codes
Stack Overflow to solve any integration problems
Original Source

How to Use Visual Event Tracking of DTM Web to Report Events to Google Analytics

The click-through rate of a web page is a critical indicator for operations personnel to understand user behavior and analyze which product content users are interested in. However, tracking events of web pages requires a lot of technical skills – skills which most operations personnel or beginners may not have. In addition, modifying tracking events can also be time consuming and difficult process. There is therefore a need to visualize and simplify event tracking, and prevent the need to frequently release new website versions when events to report are added, reduced, or modified, which has a negative impact on user experience.
This article illustrates how to use the tag template-based visual event tracking feature of DTM Web to report events in your website to Google Analytics. The following uses the example of reporting events about user's viewing of HUAWEI Mate series product details to Google Analytics, to obtain information such as the click-through rate.
Prerequisites
1. You have created an AppGallery Connect account and signed in to it by visiting the following URL address:
https://developer.huawei.com/consumer/en/service/josp/agc/index.html
2. You have created a web app and its DTM configuration.
3. You have created your website and integrated the DTM configuration script into it. To integrate the DTM configuration script, perform the following:
a. Click the Configuration tab and then View in the DTM portal.
b. Copy the code snippet below and paste it to the top of the <head> section of each web page to track, so that the code snippet takes effect in a timely manner.
{
"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"
}
Accessing the Visual Event Tracking Page
1. Click the Visual event tab in the DTM portal.
2. Click Visual event tracking by tag template in the upper right corner.
3. Click Create in the Select tag template area, set relevant parameters as follows, and click Save.
a. Enter a tag name.
b. Set Extension to Google Analytics: Universal Analytics.
c. Enter the tracking ID. (The ID is obtained from Google Analytics, and is in UA-xxxxxxxxx-x format.)
d. Use default values for other parameters.
4. Select the created tag template, and click Start in the Add area on the right.
Adding a Visual Event
1. On the Add visual event page displayed, click Add on the right.
2. Select Button or link under Select element for visual event addition. (This option is selected by default.)
3. Select the Detail button under HUAWEI Mate Series on the left page.
Click OK in the displayed dialog box asking you whether to select elements of the same type.
4. Configure visual event information.
a. Enter a visual event name.
b. Set Tracking type to Event.
c. Set Event type to {{Event}} (reference to the preset variable Event).
d. Set Event operation to Detail. (Click the hand icon next to Event type and select Detail under HUAWEI Mate Series as a same-type element parameter.)
e. Set Event label to HUAWEI Mate Xs. (Click the hand icon next to Event label and select a product name under HUAWEI Mate Series as a same-type element parameter.)
f. Use default values for other parameters.
5. Click OK to save the visual event.
6. Click the on the icon right of a visual event to expand it.
7. Click the icon in the upper left corner to exit the visual event tracking page.
Creating and Releasing a Version
1. Click Create on the Version tab page.
2. On the Create version page, enter a version name and description.
3. Select Create and release version.
4. Click OK.
Triggering a Visual Event
1. Refresh the tested website and download the latest DTM configuration.
Note: By default, the DTM JavaScript SDK downloads the latest DTM configuration to the cache every 15 minutes. To download the latest DTM configuration immediately, disable the browser cache and refresh the tested website again.
2. Click any Detail button under HUAWEI Mate Series.
Viewing Reported Data on Google Analytics
Go to Realtime > Events and view the latest reported data.
* Data is for reference only.
To learn more about DTM, click here.
For more details, you can go to:
l Our Development Documentation page, to find the documents you need
l Reddit to join our developer discussion
l GitHub to download demos and sample codes
l Stack Overflow to solve any integration problems
Check out in forum

Pygmy Collection Application Part 10 (Remote Configuration and Android Work manager)

Introduction​
If are you new to this application, please follow my previous articles
Pygmy collection application Part 1 (Account kit)
Intermediate: Pygmy Collection Application Part 2 (Ads Kit)
Intermediate: Pygmy Collection Application Part 3 (Crash service)
Intermediate: Pygmy Collection Application Part 4 (Analytics Kit Custom Events)
Intermediate: Pygmy Collection Application Part 5 (Safety Detect)
Intermediate: Pygmy Collection Application Part 6 (Room database)
Intermediate: Pygmy Collection Application Part 7 (Document Skew correction Huawei HiAI)
Intermediate: Pygmy Collection Application Part 8 (Scan kit customized view)
Intermediate: Pygmy Collection Application Part 9 (Cloud Testing)
Click to expand...
Click to collapse
In this article, I will explain what is Huawei Remote configuration? How does Huawei Remote Configuration work in Android? At the end of this tutorial, we will create the Huawei Remote Configuration Android Pygmy collection application.
In this example, I am Enabling/Disabling Export report to PDF using remote configuration. When Export PDF is enabled, user can Export report otherwise user can’t export report to PDF format instead user can just see the report in the application. And also generate PDF every 12 hour using android work manager.
What is Huawei Remote Configuration?
Huawei Remote Configuration is cloud service. It changes the behaviour and appearance of your app without publishing an app update on App Gallery for all active users. Basically, Remote Configuration allows you to maintain parameters on the cloud, based on these parameters we control the behaviour and appearance of your app. In the festival scenario, we can define parameters with the text, colour and images for a theme which can be fetched using Remote Configuration.
How does Huawei Remote Configuration work?
Huawei Remote Configuration is a cloud service that allows you to change the behaviour and appearance of your app without requiring users to download an app update. When using Remote Configuration, you can create in-app default values that controls the behaviour and appearance of your app. Then, you can later use the Huawei console or the Remote Configuration to override in-app default values for all app users or for segments of your user base. Your app controls when updates are applied, and it can frequently check for updates and apply them with a negligible impact on performance.
In Remote Configuration, we can create in-app default values that controls the behaviour and appearance (such as text, color and image etc.) in the app. Later on, with the help of Huawei Remote Configuration, we can fetch parameters from the Huawei remote configuration and override the default value.
Integration of Remote configuration
1. Configure application on the AGC.
2. Client application development process.
Configure application on the AGC
Follow the steps
Step 1: We need to register as a developer account in AppGallery Connect. If you are already developer ignore this step.
Step 2: Create an app, refer to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on current location.
Step 4: Enabling Remote configuration. Open AppGallery connect, choose Grow > Remote confihuration
Step 5: Generating a Signing Certificate Fingerprint.
Step 6: Configuring the Signing Certificate Fingerprint.
Step 7: Download your agconnect-services.json file, paste it into the app root directory.
Client application development process
Follow the steps
Step 1: Create flutter application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.6.1.300'
// For WorkManager.
implementation 'android.arch.work:work-runtime:1.0.1'
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:
<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>
To achieve Remote configuration service example, follow the steps.
1. AGC Configuration
2. Build Flutter application
Step 1: AGC Configuration
1. Sign in to AppGallery Connect and select My apps.
2. Select the app in which you want to integrate Huawei Remote configuration Service.
3. Navigate to Grow > Remote configuration > Enable
Step 2: Build Android application
In this example, I am Enabling/Disabling Export report to PDF feature from remote configuration. When export PDF feature is enabled, user can export report to the PDF. Otherwise user can’t export report.
Basically, Huawei Remote Configuration has three different configurations as explained below.
Default Configuration: In this configuration default values defined in your app, if no matching key found on remote configuration sever than default value is copied the in active configuration and returned to the client.
Java:
AGConnectConfig config = AGConnectConfig.getInstance();
Map<String, Object> map = new HashMap<>();
map.put(“test1”, “test1”);
map.put(“test2”, “true”);
map.put(“test3”, 123);
map.put(“test4”, 123.456);
map.put(“test5”, “test-test”);
config.applyDefault(map);
Fetched Configuration: Most recent configuration that fetched from the server but not activated yet. We need to activate these configurations parameters, then all value copied in active configuration.
Java:
Config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
config.apply(configValues);
// Use the configured values.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
Active Configuration: It directly accessible from your app. It contains values either default and fetched.
Fetch Parameter value
After default parameter values are set or parameter values are fetched from Remote Configuration, you can call AGCRemoteConfig.getValue to obtain the parameter values through key values to use in your app.
Java:
Config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
config.apply(configValues);
isPDFGenerateEnabled = configValues.getValueAsBoolean(“enable_pdf_generate”);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
Resetting Parameter Values
You can clear all existing parameter using below function.
Java:
Config.clearAll();
What all can be done using Huawei remote configuration
Displaying Different Content to Different Users: Remote Configuration can work with HUAWEI Analytics to personalize content displayed to different audiences. For example, officeworkers and students will see different products and UI layouts in an app.
Adapting the App Theme by Time: You can set time conditions, different app colors, and various materials in Remote Configuration to change the app theme for specific situations. For example, during the graduation season, you can adapt your app to the graduation theme to attract more users.
Releasing New Functions by User Percentage: Releasing new functions to all users at the same time will be risky. Remote Configuration enables new function release by user percentage for you to slowly increase the target user scope, effectively helping you to improve your app based on the feedback from users already exposed to the new functions.
Features of Remote configuration
1. Add parameters
2. Add conditions
1. Adding Parameters: In this you can add parameter with value as many as you want. Later you can also change the value that will be automatically reflected in the app. After adding all the required parameters, let’s release the parameter.
{
"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. Adding condition: This feature helps developer to add the conditions based on the below parameters. And conditions can be released.
App Version
OS version
Language
Country/Region
Audience
User Attributes
Predictions
User Percentage
Time
App Version: Condition can be applied on app versions. Which has four operator Include, Exclude, Equal, Include regular expression. Based on these four operators you can add conditions.
OS Version: Using the developer can add condition based on android OS version.
Language: Developer can add the condition based on the language.
Country/Region: Developer can add condition based on the country or region.
User percentage: Developer can roll feature to users based on the percentage of the users between 1-100%.
Time: Developer can use time condition to enable or disable some feature based on time. For example if the feature has to enable on particular day.
After adding required condition, release all the added conditions.
Java:
If (isPDFGenerateEnabled){
exportReport.setVisibility(View.VISIBLE);
}else {
exportReport.setVisibility(View.GONE);
}
exportReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isPDFGenerateEnabled) {
try {
List<DailyCollectionEntity> entities = PygmyDatabase.getDatabase(getActivity()).dailyCollectionDao().findCollectionsByDate(formattedDate);
List<String> headers = new ArrayList<>();
headers.add(“Shop Name”);
headers.add(“Account Number”);
headers.add(“Account Holder Number”);
headers.add(“Today’s Balance”);
headers.add(“Total Balance”);
if (entities != null && entities.size() > 0) {
String path = getStorageDir(“Date_” + formattedDate + “.pdf”);
PDFUtility.createPdf(getContext(), TodayCollectionFragment.this::onPDFDocumentClose, getTableData(entities, formattedDate), headers, path, true);
}
} catch (Exception e) {
AGConnectCrash.getInstance().recordException€;
e.printStackTrace();
Log.e(“TAG”, “Error Creating Pdf”);
Toast.makeText(getActivity(), “Error Creating Pdf”, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), “PDF Generation is disabled”, Toast.LENGTH_SHORT).show();
}
}
});
Now create work manager.
Java:
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.shea.pygmycollection.utils.FileUtils;
public class GenerateReportToPDFWorkManager extends Worker {
private static final String TAB = GenerateReportToPDFWorkManager.class.getSimpleName();
public GenerateReportToPDFWorkManager(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
FileUtils.generatePDF();
return Result.success();
}
}Copy codeCopy code
Now build the periodic work manager.
private PeriodicWorkRequest mPeriodicWorkRequest;
// Generate pdf every 12 hour
mPeriodicWorkRequest = new PeriodicWorkRequest.Builder(GenerateReportToPDFWorkManager.class,
12, TimeUnit.HOURS)
.addTag("periodicWorkRequest")
.build();
WorkManager.getInstance().enqueue(mPeriodicWorkRequest);
Result​
Tips and Tricks​
Add the dependencies properly.
Add internet permission.
If required add condition properly.
Conclusion​
In this article, we have learnt integration of Huawei Remote configuration, how to add the parameters, how to add the Conditions, how to release parameters and conditions and how to fetch the remote data in application and how to clear the data in Android Pygmy collection application.
Reference​
Huawei Remote Configuration
Happy coding

Categories

Resources