AppGallery Connect App Messaging Kit Flutter Plugin


Contents


1. Introduction

This plugin enables communication between Huawei App Messaging SDK and Cordova platform. It exposes all functionality provided by Huawei App Messaging SDK.


2. Installation Guide

Before you get started, you must register as a HUAWEI Developer and complete identity verification on the HUAWEI Developer website. For details, please refer to Register a HUAWEI ID.

Creating a Project in AppGallery Connect

Creating an app in AppGallery Connect is required in order to communicate with the Huawei services. To create an app, perform the following steps:

Step 1. Sign in to AppGallery Connect and select My projects.

Step 2. Select your project from the project list or create a new one by clicking the Add Project button.

Step 3. Go to Project Setting > General information, and click Add app. If an app exists in the project and you need to add a new one, expand the app selection area on the top of the page and click Add app.

Step 4. On the Add app page, enter the app information, and click OK.

Enabling App Messaging

You need to enable App Messaging before using it. If you have enabled it, skip this step.

Step 1. In AppGallery Connect, click My projects.

Step 2. Find your project from the project list and click the app for which you need to enable App Messaging on the project card.

Step 3: Go to Growing > App Messaging.

Step 4: Click Enable now in the upper right corner.

Step 5: The App Messaging service uses HUAWEI Analytics to report in-app message events. Therefore, you need to enable HUAWEI Analytics before integrating the App Messaging SDK. For details, please refer to Enabling HUAWEI Analytics.

For further details, please refer to Enabling App Messaging.

Integrating the Flutter App Messaging Plugin

Android App Development

Step 1: Go to Project Setting > General information page, under the App information field, click agconnect-services.json to download the configuration file.

Step 2: Copy the agconnect-services.json file to the example/android/app/ directory of your project.

Step 3: Open the build.gradle file in the example/android directory of your project.

  • Navigate to the buildscript section and configure the Maven repository address and agconnect plugin for the AppGallery Connect SDK.

    buildscript {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    
      dependencies {
          /*
            * <Other dependencies>
            */
          classpath 'com.huawei.agconnect:agcp:1.4.2.301'
      }
    }
    
  • Go to allprojects and configure the Maven repository address for the AppGallery Connect SDK.

    allprojects {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    }
    

Step 4: Open the build.gradle file in the example/android/app/ directory.

  • Add apply plugin: 'com.huawei.agconnect' line after other apply entries.

    apply plugin: 'com.android.application'
    apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
    apply plugin: 'com.huawei.agconnect'
    
  • Set your package name in defaultConfig > applicationId and set minSdkVersion to 19 or higher. Package name must match with the package_name entry in agconnect-services.json file.

    defaultConfig {
        applicationId "<package_name>"
        minSdkVersion 19
        /*
        * <Other configurations>
        */
    }
    

Step 5: Edit buildTypes as follows:

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.debug
        }
    }

iOS App Development

Step 1: Go to Project Setting > General information page, under the App information field, click agconnect-services.plist to download the configuration file.

Step 2: Copy the agconnect-services.plist file to the app's root directory of your Xcode project.

NOTE Debugging Flutter

Other launch paths without a host computer, such as deep links or notifications, won't work on iOS 14 physical devices in debug mode. You can also build the application or add-to-app module in profile or release mode, or on a simulator, which are not affected. For more details please refer to information

Add to Library

Step 1: On your Flutter project directory, find and open your pubspec.yaml file and add the agconnect_appmessaging library to dependencies. For more details please refer to the Using packages document.

  • To download the package from pub.dev.

      dependencies:
        agconnect_appmessaging: {library version}
    

Step 2: Run the following command to update package info.

[project_path]> flutter pub get

Step 3: Import the library to access the methods.

import 'package:agconnect_appmessaging/agconnect_appmessaging.dart';

Step 4: Run the following command to start the app.

[project_path]> flutter run

3. API Reference

AgconnectAppmessaging

Contains classes that provide methods to represents the message processing class.

Public Constructor Summary

ConstructorDescription
AgconnectAppmessaging()Default constructor.

Public Method Summary

MethodReturn TypeDescription
isDisplayEnable()Future<bool>This API is called to checks whether the App Messaging SDK is allowed to display in-app messages.
setFetchMessageEnable(bool enable)Future<void>This API is called to sets whether to allow the App Messaging SDK to synchronize in-app message data from the AppGallery Connect server.
setDisplayEnable(bool enable)Future<void>This API is called to sets whether to allow the App Messaging SDK to display in-app messages.
isFetchMessageEnable()Future<bool>This API is called to checks whether the App Messaging SDK is allowed to synchronize in-app message data from the AppGallery Connect server.
setForceFetch()Future<void>This API is called to sets the forcible in-app message data obtaining flag. When the flag is enabled, you can obtain latest in-app message data from the AppGallery Connect server in real time. This method is only to support on Android Platform.
removeCustomView()Future<void>This API is called to remove custom in-app message layout. Then the default layout will be used.
setDisplayLocation(int locationConstant)Future<void>This API is called to sets the display position of a pop-up or image message.
trigger(String eventId)Future<void>This API is called to triggers a custom event.
handleCustomViewMessageEvent(Map<String, dynamic> map)Future<void>This API is called to while using custom app message layout, handle custom app message click events.
onMessageDismiss()Stream<Appmessage>This API is called to adds a listener for dismiss event.
onMessageClick()Stream<Appmessage>This API is called to adds a listener for click event.
onMessageDisplay()Stream<Appmessage>This API is called to adds a listener for display event.
onMessageError()Stream<Appmessage>This API is called to adds a listener for error event.
customEvent()Stream<Appmessage>This API is called to adds a listener for custom event.

Public Constructors

AgconnectAppmessaging()

Constructor for AgconnectAppmessaging object.

Public Methods

Future<bool> isDisplayEnable() async

Checks whether to allow the App Messaging SDK to display in-app messages.

Return TypeDescription
Future<bool>Indicates whether to allow the App Messaging SDK to display in-app messages.
Call Example
 try {
      bool isDisplayEnable = await agconnectAppmessaging.isDisplayEnable();
      print(isDisplayEnable.toString());
      _showDialog(context, isDisplayEnable.toString());
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<void> setFetchMessageEnable(bool enable) async

Sets whether to allow the App Messaging SDK to synchronize in-app message data from the AppGallery Connect server.

ParameterDescription
enableIndicates whether to allow the App Messaging SDK to synchronize in-app message data from the AppGallery Connect server. The options are as follows:
true: yes
false: no.
The default value is true.
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    try {
      agconnectAppmessaging.setFetchMessageEnable(true);
      _showDialog(context, 'setFetchMessageEnable true');
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<void> setDisplayEnable(bool enable) async

Sets whether to allow the App Messaging SDK to display in-app messages.

ParameterDescription
enableIndicates whether to allow the App Messaging SDK to display in-app messages.The options are as follows:
true: yes
false: no
The default value is true.
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    try {
      agconnectAppmessaging.setDisplayEnable(true);
      _showDialog(context, 'setDisplayEnable true');
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<bool> isFetchMessageEnable() async

Checks whether to allow the App Messaging SDK to synchronize in-app message data from the AppGallery Connect server.

Return TypeDescription
Future<bool>Indicates whether to allow the App Messaging SDK to synchronize in-app message data from the AppGallery Connect server. The options are as follows:
true: yes
false: no
Call Example
    try {
      bool isFetchMessageEnable =
          await agconnectAppmessaging.isFetchMessageEnable();
      print(isFetchMessageEnable.toString());
      _showDialog(context, isFetchMessageEnable.toString());
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<void> setForceFetch() async

Sets the flag for whether to obtain in-app message data from the AppGallery Connect server in real time by force.

After this method is called, the App Messaging SDK does not immediately request data from the AppGallery Connect server. When the next trigger event takes place, the App Messaging SDK forcibly obtains in-app message data from the AppGallery Connect server. For iOS platform: Enable the debugging mode for your app. Add the '-AGConnectDeveloperMode' launch parameter to the app scheme. Start your app in Xcode debug mode. Notice:

  • The setForceFetch API can be used only for message testing.
  • The forcible data obtaining flag is bound to the AAID of the test device. After you uninstall and reinstall the app or clear app data on the device, the flag will be reset.
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
  Future<void> _setForceFetch(BuildContext context) async {
    try {
      agconnectAppmessaging.setForceFetch();
      _showDialog(context, 'setForceFetch');
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }
  }

Future<void> removeCustomView() async

Remove custom in-app message layout. Then the default layout will be used.

Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    try {
      agconnectAppmessaging.removeCustomView();
      _showDialog(context, "removeCustomView");
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<void> setDisplayLocation(int locationConstant) async

Sets the display position of a pop-up or image message.

ParameterDescription
locationConstantLocation instance..
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    try {
      agconnectAppmessaging
          .setDisplayLocation(AppMessagingLocationConstants.CENTER);
      _showDialog(context, 'setDisplayLocation');
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }

Future<void> trigger(String eventId) async

Triggers a custom event.

ParameterDescription
eventIdID of a custom event..
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    try {
      agconnectAppmessaging.trigger("OnAppForeGround");
      _showDialog(context, 'trigger');
    } on PlatformException catch (e) {
      _showDialog(context, e.toString());
    }
Future<void> handleCustomViewMessageEvent(Map<String, dynamic> map) async

While using custom app message layout, handle custom app message click events.

ParameterDescription
mapWhen using custom app message layout, handle custom app message click events like below, gets eventType ( AppMessagingEventType.onMessageDisplay, AppMessagingEventType.onMessageClick, AppMessagingEventType.onMessageDismiss(String dismissType), AppMessagingEventType.onMessageError and dismissType param( AppMessagingDismissTypeConstants.CLICK, AppMessagingDismissTypeConstants.CLICK_OUTSIDE, AppMessagingDismissTypeConstants.AUTO, AppMessagingDismissTypeConstants.BACK_BUTTON, AppMessagingDismissTypeConstants.SWIPE) when using AppMessagingDismissTypeConstants.onMessageDismiss(String dismissType).
Return TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
    _streamSubscription1 = agconnectAppmessaging.customEvent.listen((event) {
      print('customEvent       $event');
      agconnectAppmessaging.handleCustomViewMessageEvent
        (AppMessagingEventType.onMessageDismiss(AppMessagingDismissTypeConstants.CLICK));
    });

Stream<AppMessage> get onMessageDismiss async

Add a listener to obtain app message dismiss events.

Return TypeDescription
Stream<AppMessage>AppMessage data to be processed, which is returned asynchronously.
Call Example
    _streamSubscription = agconnectAppmessaging.onMessageDismiss.listen((event) async {
      print(event.toString());

    });

Stream<AppMessage> get onMessageClick async

Add a listener to obtain app message click events.

Return TypeDescription
Stream<AppMessage>AppMessage data to be processed, which is returned asynchronously.
Call Example
    _streamSubscription = agconnectAppmessaging.onMessageClick.listen((event) async {
      print(event.toString());

    });

Stream<AppMessage> get onMessageDisplay async

Add a listener to obtain app message display events.

Return TypeDescription
Stream<AppMessage>AppMessage data to be processed, which is returned asynchronously.
Call Example
    _streamSubscription = agconnectAppmessaging.onMessageDisplay.listen((event) async {
      print(event.toString());

    });

Stream<AppMessage> get onMessageError async

Add a listener to obtain app message error events.

Return TypeDescription
Stream<AppMessage>AppMessage data to be processed, which is returned asynchronously.
Call Example
    _streamSubscription = agconnectAppmessaging.onMessageError.listen((event) async {
      print(event.toString());

    });

Stream<AppMessage> get customEvent async

Add a listener to obtain app message customEvent events.

Return TypeDescription
Stream<AppMessage>AppMessage data to be processed, which is returned asynchronously.
Call Example
    _streamSubscription = agconnectAppmessaging.customEvent.listen((event) async {
      print(event.toString());

    });

Public Constants

AppMessagingLocationConstants

  • Display position of a pop-up or image message.
FieldValueDescription
BOTTOM0Bottom.
CENTER1Center.

AppMessagingDismissTypeConstants

  • Message closing constants.
FieldTypeDescription
CLICKStringClose button or redirection link tapping.
CLICK_OUTSIDEStringTapping outside the message borders.
BACK_BUTTONStringBack button tapping.
AUTOStringAuto.
SWIPEStringSWIPE.

AppMessagingEventType

  • Custom events constants for event callbacks.
FieldTypeDescription
onMessageDisplayStringListens on message display events.
onMessageClickStringListens on message tap events.
onMessageErrorStringListens on message error events.
onMessageDismiss(String dismissType)StringListens on message closing events.
AppMessage
  • Represents the app message data.
FieldTypeDescription
idStringObtains the ID of an in-app message.
messageTypeStringObtains the message type.
startTimeintObtains the start timestamp of a message.
endTimeintObtains the end timestamp of a message.
frequencyTypeintObtains the display frequency type of a message.
frequencyValueintObtains the display frequency of a message.
testFlagintChecks whether an in-app message is a test message.
dismissTypeStringObtains the dismiss type.
triggerEventsListObtain the ID of a trigger event.
bannerMessageBannerMessageObtains the banner information of a message.
cardMessageCardMessageObtains the card information of a message.
pictureMessagePictureMessageObtains the picture information of a message.
Call Example
    _streamSubscription =
        agconnectAppmessaging.onMessageDisplay.listen((event) {
      print(event.startTime);
    });
BannerMessage
  • Represents a banner message.
FieldTypeDescription
titleStringObtains the title of a banner message.
titleColorStringObtains the title color of a banner message.
titleColorOpennessnumObtains the title color transparency of a banner message.
bodyStringObtains the body of a banner message.
bodyColorStringObtains the body color of a banner message.
bodyColorOpennessnumObtains the body color transparency of a banner message.
backgroundColorStringObtains the background color of a banner message.
backgroundColorOpennessnumObtains the background color transparency of a banner message.
pictureUrlStringObtains the image URL of a banner message.
actionUrlStringObtains the redirection URL in a banner message.
Call Example
    _streamSubscription =
        agconnectAppmessaging.onMessageDisplay.listen((event) {
      print(event.cardMessage.backgroundColor);
    });
CardMessage
  • Represents a pop-up message.
FieldTypeDescription
titleStringObtains the title of a pop-up message.
titleColorStringObtains the title color of a pop-up message.
titleColorOpennessnumObtains the title color transparency of a pop-up message.
bodyStringObtains the body of a pop-up message.
bodyColorStringObtains the body color of a pop-up message.
bodyColorOpennessnumObtains the body color transparency of a pop-up message.
backgroundColorStringObtains the background color of a pop-up message.
backgroundColorOpennessnumObtains the background color transparency of a pop-up message.
portraitPictureURLStringObtains the URL of the portrait image for a pop-up message.
landscapePictureURLStringObtains the URL of the landscape image for a pop-up message.
majorButtonButtonObtains the primary button of a pop-up message.
minorButtonButtonObtains the secondary button of a pop-up message.
Call Example
    _streamSubscription1 =
        agconnectAppmessaging.onMessageDismiss.listen((event) {
          print(event.cardMessage.bodyColor);
    });
PictureMessage
  • Represents an image message.
FieldTypeDescription
pictureURLStringImage URL of an image message.
actionURLStringObtains the redirection URL of an image message.
Call Example
    _streamSubscription1 =
        agconnectAppmessaging.onMessageDisplay.listen((event) {
          print(event.pictureMessage.pictureURL);
    });
Button
  • Represents a pop-up message button.
FieldTypeDescription
textStringObtains the button name.
textColorStringObtains the button name text color.
textColorOpennessnumObtains the transparency of the button name text color.
actionURLStringObtains the redirection URL of the button.
Call Example
    _streamSubscription1 =
        agconnectAppmessaging.onMessageDisplay.listen((event) {
          print(event.cardMessage.majorButton.text);
    });

4. Configuration and Description

Configuring Obfuscation Scripts

Before building the APK, configure obfuscation scripts to prevent the AppGallery Connect SDK from being obfuscated. If obfuscation arises, the AppGallery Connect SDK may not function properly. For more information on this topic refer to this Android developer guide.

<flutter_project>/android/app/proguard-rules. pro

-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agc.**{*;}
-keep class com.huawei.agconnect.**{*;}

## Flutter wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.**  { *; }
-keep class io.flutter.util.**  { *; }
-keep class io.flutter.view.**  { *; }
-keep class io.flutter.**  { *; }
-keep class io.flutter.plugins.**  { *; }
-dontwarn io.flutter.embedding.**
-keep class com.huawei.agc.flutter.** { *; }
-repackageclasses

<flutter_project>/android/app/build.gradle

buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {

        // Enables code shrinking, obfuscation and optimization for release builds
        minifyEnabled true
        // Unused resources will be removed, resources defined in the res/raw/keep.xml will be kept.
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

	signingConfig signingConfigs.config
    }
}

Listening for AppMessaging Events

Add a listener to obtain app message click events.

Call Example
 @override
  void initState() {
    super.initState();

    _streamSubscriptionDisplay =
        agconnectAppmessaging.onMessageDisplay.listen((event) {
      print('onMessageDisplay       $event');
    });
    _streamSubscriptionClick =
        agconnectAppmessaging.onMessageClick.listen((event) {
      print('onMessageClick       $event');
    });
    _streamSubscriptionDismiss =
        agconnectAppmessaging.onMessageDismiss.listen((event) {
      print('onMessageDismiss       $event');
    });

    _streamSubscriptionError =
        agconnectAppmessaging.onMessageError.listen((event) {
      print('onMessageError       $event');
    });
  }

Adding Custom View

App Messaging supports three messages types, namely pop-up, image, and banner messages. The App Messaging SDK provides a default layout for each type. You can customize the message display style that better suits your app to provide personalized experience for users.

Firstly, add a listener to obtain app message. Then you can create your own layout for app message.

    _streamSubscription1 = agconnectAppmessaging.customEvent.listen((event) {
      _showDialog(context ,event.toString());
    });

Below lines should be added to the corresponding platforms.

IOS:

Add the following code in AppDelegate to your project:

Set AGCCustomView field in your Flutter/iOS project info.plist file.

true: adding custom view false: removing custom view

<dict>
    ...
    <key>AGCCustomView</key>
    <false/>
    ...
</dict>

Android:
You should add below code to the onCreate method of MainActivity.java.

AGCAppMessagingCustomEventStreamHandler.addCustomView();

Accessing Analytics Kit

To use analytics feature,

  • Navigate into your /android/app/build.gradle and add build dependencies in the dependencies section.

      dependencies {
          implementation 'com.huawei.hms:hianalytics:5.1.0.301'
      }
    
  • Navigate into your /ios file and edit the Podfile file to add the pod dependency 'HiAnalytics'

    • Example Podfile file:

        # Pods for AGCAppMessagingDemo
        pod 'HiAnalytics'
      
    • Run pod install to install the pods.

       $ pod install
      
    • Initialize the Analytics SDK using the config API in AppDelegate in iOS platform.

      Sample code for initialization in AppDelegate:

      import UIKit
      import Flutter
      import HiAnalytics
    
      @UIApplicationMain
      @objc class AppDelegate: FlutterAppDelegate {
              override func application(
              _ application: UIApplication,
              didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
              ) -> Bool {
            // Initialize the Analytics SDK.
            HiAnalytics.config();  
    
              GeneratedPluginRegistrant.register(with: self)
              return super.application(application, didFinishLaunchingWithOptions: launchOptions)
          }
      }
    

    For further information please refer to Analytics Kit Service Guide.


5. Sample Project

This plugin includes a demo project in the example folder, there you can find more usage examples.


6. Licensing and Terms

AppGallery Connect App Messaging Kit Flutter Plugin is licensed under Apache 2.0 license

Libraries

agconnect_appmessaging
app_message
app_messaging