Remote Configuration allows you to change how your app works and looks on the cloud, without requiring any app upgrades. Here we’ll take a look at a hands-on example of how to integrate Remote Configuration.
Enabling and Configuring Remote ConfigurationSign in to AppGallery Connect and click My projects.
Click your project card and select the app for which you want to enable Remote Configuration from the app drop-down list on the top.
Go to Grow > Remote Configuration. If this is your first time using Remote Configuration, click Use now in the upper right corner.
{
"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"
}
Then you’ll be able to configure the service in AppGallery Connect.
On the Remote Configuration page, set parameter and their conditions.
First, click New parameter to add a parameter. You can set multiple conditional values for a parameter. That is, the parameter value will vary depending on the condition.
Click Save.
Click Release to make the configuration take effect. If you click Cancel, all changes will be discarded.
Click the Parameters tab, on which all parameters are listed.
Click in the upper right corner of the parameter card. You’ll be able to view, modify, and delete parameters, and copy existing parameters as new ones.
On the Conditions tab, you can set different conditions for the parameter. For example, if you set Condition to Audience, the configured parameter value will be updated only for a specific user group.
Integrating SDKsAdd Maven repository configuration to the build.gradle file of your project
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Open the app-level build.gradle file, and configure the Remote Configuration SDK, Analytics SDK, and AppGallery Connect Plugin
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
android {...}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.5.2.300'
}
In AppGallery Connect, click My projects, and find your project from the list. Go to Project settings > General information, download the agconnect-services.json file, and save the file to the app directory of your Android project.
Developing FunctionsIn this step, the Remote Configuration SDK will be used to set in-app default values and fetch parameter values from the cloud.
Add a default value configuration XML file, for example, remote_config.xml, to the res/xml directory of your Android Studio project. In the file, key-value pairs are in testvalue format.
Call applyDefault to pass the default values.
Code:
config.applyDefault(R.xml.remote_config);
You can also create a Map object, and call applyDefault to read and pass the default values.
You can apply parameter values fetched from the cloud either immediately or upon the next launch of your app.
Fetch parameter values and apply them immediatelyThe following code applies parameter values immediately.
Code:
config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
config.apply(configValues);
// Apply parameter values.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
In the code, call the fetch API to fetch parameter values from the cloud, and then call the apply API to apply the parameter values in the fetching callback immediately.
Fetch parameter values and apply them upon the next launch of your app.The following code applies parameter values upon the next launch of your app.
Code:
ConfigValues last = config.loadLastFetched();
config.apply(last);
config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
In the code, call loadLastFetched to obtain the parameter values fetched by calling the fetch API, and call the apply API to apply the parameter values.
Obtain the value for a single parameterYou can call an API to obtain the value for a parameter of a specific type from parameter values fetched from the cloud. The APIs for different parameter types are listed below
Code:
Boolean value = config.getValueAsBoolean("key");
Double value = config.getValueAsDouble("key");
Long value = config.getValueAsLong("key");
String value = config.getValueAsString("key");
byte[] value = config.getValueAsByteArray("key");
Obtain all parameter valuesYou can obtain all in-app default parameter values and on-cloud parameter values by calling getMergedAll.
Code:
Map<String,Object> map = config.getMergedAll();
For details, please refer to the development guide for Remote Configuration.
Will it works on offline?
Thanks for sharing!!!
Related
Introduction
Often, when you take screenshots of text and images you find online and share them with your friends, the apps you use to send them will automatically compress the screenshots. This means the people receiving them get low definition images which are hard to read.
Is there any way to solve this problem? Of course! ML Kit's text super-resolution capability improves text resolution in images. It enables users to magnify images containing text until they're 9 times bigger while greatly enhancing the text’s definition, making it easier to read.
Application Scenarios
The text super-resolution capability is useful in a huge range of situations. For example, when screenshots are compressed, the text super-resolution capability will restore them to their original definition.
When you take a photograph of a document from far away, or can't properly adjust the focus, the text may not be clear. In this situation, you can use the text super-resolution capability to improve the definition and readability of the document.
Pretty useful, right? Below, I'll show you how to integrate this capability
Text Super-Resolution Development
1. Configure the Maven Repository Address
1.1 Open the build.gradle File in the Root Directory of Your Android Studio Project
{
"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"
}
1.2 Add the AppGallery Connect Plug-in and the Maven Repository
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
Code:
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
2. Integrate the Text Image Super-Resolution SDK
2.1 Full SDK Integration (Recommended)
Code:
dependencies{
// Import the base SDK.
Implementation 'com.huawei.hms:ml-computer-vision-textimagesuperresolution:2.0.3.300'
// Import the text image super-resolution model package.
implementation 'com.huawei.hms:ml-computer-vision-textimagesuperresolution-model:2.0.3.300'
}
2.2 Add Configurations to the File Header
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
2.3 Update the Machine Learning Model
Code:
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value= "tisr"/>
3. Code Development
3.1 Create a Text Image Super-Resolution Analyzer
Code:
MLTextImageSuperResolutionAnalyzer analyzer = MLTextImageSuperResolutionAnalyzerFactory.getInstance().getTextImageSuperResolutionAnalyzer();
3.2 Create an MLFrame Object by Using android.graphics.Bitmap
The bitmap type must be ARGB8888. If it isn’t, you’ll need to convert it.
Code:
// Create an MLFrame object using the bitmap. The bitmap parameter indicates the input image.
MLFrame frame = new MLFrame.Creator().setBitmap(bitmap).create();
3.3 Processing Super-Resolution for Images That Contain Texts
Code:
Task<MLTextImageSuperResolutionResult> task = analyzer.asyncAnalyseFrame(frame);
task.addOnSuccessListener(new OnSuccessListener<MLTextImageSuperResolutionResult>() {
public void onSuccess(MLTextImageSuperResolutionResult result) {
// Processing logic for super-resolution success.
}})
.addOnFailureListener(new OnFailureListener() {
public void onFailure(Exception e) {
// Processing logic for super-resolution failure.
if (e instanceof MLException) {
MLException mlException = (MLException)e;
// Obtain the result code. You can process the result code and customize the messages displayed to users.
int errorCode = mlException.getErrCode();
// Obtain the error information. You can quickly locate the fault based on the result code.
String errorMessage = mlException.getMessage();
} else {
// Other errors.
}
});
3.4 Stop the Analyzer to Release Detection Resources Once the Super-Resolution is Complete
Code:
if (analyzer != null) {
analyzer.stop();
}
GitHub Source Code
How far it can detect the text using camera ?
With the release of AppGallery Connect version 1.5.2 the Auth service now has full support for making use of unified sign-in with a Google account!
This new functionality makes AppGallery Connect Auth a great option for all of your app’s authentication needs both on Huawei devices and other Android devices.
So how do we go about using unified sign-in with a Google account? Let’s take a look!
Preparing the environment for Google Sign-inDetails: Google Identity
Navigate to your Google API&Services console.
Open the API&Services and click My Project on the upper left corner. You can create one if no project exists.
{
"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"
}
Then, click CREATE CREDENTIALS to create an OAuth client ID for your project. If you haven’t already configured the consent screen for this project, follow the on-screen instructions to configure it.
After the configuration is complete, you can navigate back to Credentials > Create CREDENTIALS > OAuth client ID to continue. Select Android as the application type and configure the package name and the SHA-1 certificate fingerprint of the JKS file. The SHA-1 certificate fingerprint here is the SHA-1 value generated in step 3. (If this step is not performed, the timeout error code 10 will be displayed when you integrate Google sign-in.)
After the Android OAuth client has been created, go to the settings page, click Web client (auto-created by Google Service) and copy Client ID and Client secret which are needed for integrating Google sign-in.
Add a resource file. Set app_id and client_id in the /app/res/values/strings.xml of the Android project. The value of client_id is Client ID in the previous step and the value of app_id is the string of numbers that starts with the Client ID.
XML:
<string name="google_app_id">81792xxxx258</string>
<string name="google_client_id">81792xxxx2258-m8crjg1xxxxxxx3kufvbji0amlp.apps.googleusercontent.com</string>
Now that everything is ready, let’s move on to enabling Auth Service.
Enabling Auth ServiceSign in to AppGallery Connect, create a project and an app, and enable Auth Service. You need to enter the Client ID and Client secret when enabling Google account authentication.
As covered in the previous step, these two can be found by going to Google API&Services > Credentials > OAuth 2.0 Client IDs and opening Web client (Auto-created for Google Sign-in).
Generating the certificate fingerprint for your Android projectIf the app does not have a JKS certificate, go to Generate Signed Bundle or APK and click Create a new key store to create one. The generated JKS certificate is the JKS file used in Step 1.
Generate an SHA-256 certificate fingerprint by running the following command and entering the configured password. The SHA1 value must be identical to that configured in step 1.
keytool -list -v -keystore you_path\AuthDemo-Union\app\authdemounion.jks
Configure the corresponding Gradle file, open the app-level build.gradle file, and configure the certificate. Click here to view more details.
Configure the generated SHA256 certificate fingerprint in AppGallery Connect. (If you do not perform this step, error 6003 is reported.)
Configuring the Android serviceOpen the project-level build.gradle file and configure the Maven repository address and other parameters, as follows:
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // config this maven
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.huawei.agconnect:agcp:1.5.1.300' // config this path
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // config this maven
}
}
Open the app-level build.gradle file and configure the SDK, app plug-in address and other parameters, as follows:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect' // config this apply
android {…}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "com.huawei.agconnect:agconnect-auth-google:1.5.2.201" // config this SDK
implementation 'com.huawei.agconnect:agconnect-auth:1.5.2.201' // config this SDK
}
Example sign in code:
Code:
private void GoogleIDLogin(){
Log.i("AuthDemo", "start:" );
AGConnectAuth.getInstance().signIn(this, AGConnectAuthCredential. Google_Provider)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
Log.i("AuthDemo", "success:" + user);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
Log.i("AuthDemo", "failed:" + e.getMessage());
}
});
}
// Lifecycle required by the unified channel.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data);
}
ResultOnce you run the app that has been configured with the signature file in an Android phone and call the GoogleIDLogin method, the following page will appear.
After completing authorization and sign-in, you can view the following logs, which indicate the authentication and sign-in are successful.
Compared with the traditional authentication mode, unified sign-in has significantly improved development, and for this reason, we strongly recommend that you leverage this function.
References:
Auth Service for Android
Google sign-in integration in Auth Service
Does it support non-Huawei phones as well?
Basavaraj.navi said:
Does it support non-Huawei phones as well?
Click to expand...
Click to collapse
it does yes! this can be used across all android devices
With the release of AppGallery Connect version 1.5.2 the Auth service now has full support for making use of unified sign-in with a Facebook account!
This new functionality makes AppGallery Connect Auth a great option for all of your app’s authentication needs both on Huawei devices and other Android devices.
So how do we go about using unified sign-in with a Facebook account? Let’s take a look!
Configuring the Facebook Login EnvironmentFirst, you’ll need to configure the Facebook Login environment.
Select or create a Facebook app.
{
"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"
}
Edit your resource file. Copy the following code to the /app/res/values/strings.xml file of your Android project.
Edit your manifest file. Add the following uses-permission element following the application element in the /app/manifest/AndroidManifest.xml file of your Android project.
Copy the following meta-data element to the application element.
Associate your package name and default activity class with your app and click Save. Confirm the use of this package name (skip this if your app has not been released on Google Play).
Develop a key hash using the following command, and release it for your app.
If you haven’t installed OpenSSL (openssl-for-windows) for your project, please go to Google Code Archive and download it as required.
keytool -exportcert -alias authdemounion -keystore F:\1.test\4.Auth\AuthDemo-Union\app\authdemounion.jks | openssl sha1 -binary | openssl base64
The command format is as follows:
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH* | openssl sha1 -binary | openssl base64
The Facebook Login environment has now been successfully configured. Let’s move on to the operations relevant to Auth Service.
Enabling Auth ServiceSign in to AppGallery Connect, create a project and an app, and enable Auth Service. You’ll need to enter the App ID and App Secret for your app when enabling Facebook under Authentication modes, which can be found under Settings > Basic on Facebook for Developers. If they are not displayed, click the button following App Secret to show them.
Generating the Certificate Fingerprint for Your Android ProjectIf the demo project does not provide a Java KeyStore, go to Generate Signed Bundle or APK and click Create new.key store to create one
Generate an SHA-256 certificate fingerprint. Run the following command and enter the configured password to generate a SHA-256 certificate fingerprint.
keytool -list -v -keystore you_path\AuthDemo-Union\app\authdemounion.jks
Open the app-level build.gradle file, and configure the certificate information for your project
Click here to view the sample code.
Configure the generated SHA-256 certificate fingerprint in AppGallery Connect. (If you do not perform this step, error 6003 will be reported.)
Configure Your AppOpen the project-level build.gradle file and configure information, including the Maven repository address. The code is as follows:
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.huawei.agconnect:agcp:1.5.1.300' // Configure this path.
// NOTE: Do not copy your dependencies in here, which should be included
// in the build.gradle files of each module.
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
}
Open the app-level build.gradle file and configure information, including the SDK information and app plug-in address. The code is as follows:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect' // Configure the apply plug-in.
android {…}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "com.huawei.agconnect:agconnect-auth-facebook:1.5.2.201" // Configure this SDK.
implementation 'com.huawei.agconnect:agconnect-auth:1.5.2.201' // Configure this SDK.
}
Add the code for implementing unified sign-in:
Java:
private void FaceBookLogin(){
Log.i("AuthDemo", "start:" );
AGConnectAuth.getInstance().signIn(this, AGConnectAuthCredential.Facebook_Provider)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
Log.i("AuthDemo", "success:" + user);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
Log.i("AuthDemo", "failed:" + e.getMessage());
}
});
}
// Activity lifecycle required by the unified sign-in.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data);
Viewing the Result and LogsOnce you run your signed APK on an Android phone and call the FaceBookLogin method, you’ll get the following page.
You can tap CONTINUE AS LINKING and sign in to your app with your Facebook account. The following log information will be displayed.
Compared with the traditional implementation mode, the unified sign-in has greatly simplified the development process. It is strongly recommended that you use the new mode.
For details about Auth Service, please refer to:
Auth Service document for Android
Guide for integrating Facebook account
Thanks for sharing.
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 projectSign 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 SDKAdd dependenciesStart 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 MessageIf 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 LayoutAdd 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 MessageApp 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
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.
Lets take a look today at how we can set this up to work within an Android 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!
Enabling the ServiceSign 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.
{
"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"
}
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 SDKAdd Maven repository configuration to the build.gradle file of your project.
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Open the app-level build.gradle file and configure the App Messaging SDK
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
android {…..}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.5.2.300'
}
In AppGallery Connect, click My projects, and find your project from the list. Go to Project settings > General information, download the agconnect-services.json file, and save the file to the app directory of your Android project.
Displaying an In-App MessageIf 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 LayoutFirst, you need to customize a message display class. To do so, implement AGConnectAppMessagingDisplay and override the displayMessage method.
Code:
public class CustomDisplayView implements AGConnectAppMessagingDisplay {
@Override
public void displayMessage(@NonNull AppMessage appMessage,
@NonNull AGConnectAppMessagingCallback callback) {
}
}
Define an AlertDialog in displayMessage and copy the layout file to the code. The sample code is as follows:
Code:
@Override
public void displayMessage(@NonNull AppMessage appMessage, @NonNull AGConnectAppMessagingCallback callback) {
Log.d(TAG, appMessage.getId() + "");
showDialog(appMessage, callback);
}
private void showDialog(@NonNull final AppMessage appMessage, @NonNull final AGConnectAppMessagingCallback callback) {
View view = LayoutInflater.from(activity).inflate(R.layout.custom_view, null, false);
final AlertDialog dialog = new AlertDialog.Builder(activity).setView(view).create();
Button click = view.findViewById(R.id.click);
Button dismiss = view.findViewById(R.id.dismiss);
TextView id = view.findViewById(R.id.id);
id.setText("MessageID: " + appMessage.getId());
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set button callback
callback.onMessageClick(appMessage);
callback.onMessageDismiss(appMessage, AGConnectAppMessagingCallback.DismissType.CLICK);
dialog.dismiss();
}
});
dismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//set button callback
callback.onMessageDismiss(appMessage, AGConnectAppMessagingCallback.DismissType.CLICK);
dialog.dismiss();
}
});
dialog.show();
dialog.getWindow().setLayout((getScreenWidth(activity) / 4 * 3), LinearLayout.LayoutParams.WRAP_CONTENT);
callback.onMessageDisplay(appMessage);
}
Call addCustomView to implement the custom layout.
Code:
CustomView customView = new CustomView(MainActivity.this);
appMessaging.addCustomView(customView);
Test in app messageObtain the Anonymous Application Identifier (AAID) of your test device, which is used to identify app instances running on mobile devices during app installation. Compared with device-level hardware IDs that cannot be reset, the privacy of AAID is much higher. We can obtain the AAID through coding.
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 need to test, and click Test in the Operation column.
Click Add test user and enter the AAID in the test box.
Click Save. Check whether the test message can be properly displayed and operated.
For details, please refer to the development guide of App Messaging.