Introduction

This Tutorial aims to teach the user how to integrate his native Flutter app with Appgain.io cloud using appgain.io SDK and how to use the appgain.io products

To integrate the Appgain SDK in your flutter app, you have to use the native SDK libraries; We will use the platform channels method, for more information about running native code in flutter apps, please visit the flutter dev guide

For a flutter application integrated with Appgain SDK for ios and android, please refer to our Appgain Flutter TestApp

You will find some supporting files to copy to your app to make your integration more easily.

Required For Setup

Installation

  • add Appgain.dart to your project

  • add those lines into your App Entry Point to initialize Appgain SDK

// var data =  {'appId':'YOUR APP ID','apiKey':'YOUR API KEY','configure':'true'};
  Future initAppgainSDK(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_initalizeAppgainSDK, data)
          .then((result) {
            print(result.toString());
      });
    } on PlatformException catch (e) {
     print(e.toString());
    }
  }

Deferred Deep Linking

After a new user has installed your app, our SDK will detect if the app was installed from a smart deep link or not, if it's then our SDK will automatically route their flow to marketing campaign desired location in the app (not just to the default home screen).

To achieve that, appgain.io SDK must be installed in the app, and the matching process must be initiated


Future matchLink() async {
    try {
      await appgainPlatform
          .invokeMethod(_createMatchLink, '')
          .then((result) {
            //do your success handling , like getting the data out of response object

      });
    } on PlatformException catch (e) {
      print(e.toString());
    }
  }

The following data are returned on matching success :

Returned Field Description
smart_link_url the URL of smart deep link used to open or install the App
smart_link_id the Id of smart deep link used to open or install the App
smart_link_name the Id of smart deep link used to open or install the App
match_type how the device identification done , it could be basic(Digital fingerprinting) or advertising_id
extra_data array of more data
extra_data.userId user Id that was appended to smart link url on opening it phase
params array of all paramaters appended to smart link url , like SDL URL?utm_source=fb
smart_link_primary primary redirection action

Marketing Automation

Send Automated and Personalized Push notifications, SMS or Emails based on your user's actions and behavior using Apggain's Powerful Automator, Know More Now!

  1. Create an auto message in Appgain Dashboard .

  2. Fire the auto message by using this code.

  3. you must use the same trigger event that was entered in step 1, as the TriggerPoint in the following code.

without Personalization



  //  var data = {'triggerPointName':'AUTOMATOR TRIGGER POINT NAME'};
  Future fireAutomator(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_createfireAutomator, data)
          .then((result) {
            print(result.toString());
      });
    } on PlatformException catch (e) {
      print(e.toString());

    }
  }

with Personalization


// var data = {'triggerPointName':'value','personalizationMap':{'name':'jone','cartname':'sports'}};
  Future fireAutomatorWithPersonalization(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_createfireAutomatorWithPersonalization, data)
          .then((result) {
            TextFieldAlertDialog().showAlertDialog(result.toString());
      });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }
  }

Revenue Tracking

you can add new Purchase Transactions object by using the following snippet :


//Output : -  callback with two parameter
  ///success bool   as string
  ///error
  //var data = {'productName':'value','curruncy':'value','amount':22};
  Future addPurchase(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_logNewPurchase, data)
          .then((result) {
        TextFieldAlertDialog().showAlertDialog( result.toString());
      });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }

App Events Logging

at your app whenever you want to log AppEvent, add the following snippet :

//MARK: log event
//type (String)
//action (String)

// Output : -  callback with two parameter
  ///   response  as string
  ///    info dictionary
  Future logEvent(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_logEventwith, data)
          .then((result) {
            TextFieldAlertDialog().showAlertDialog(result.toString());
      });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }
  }


}

Add Custom User Property

at your app whenever you want to Add Custom User Property , add the following snippet :


//MARK: update user profile
//Output : -  callback with two parameter
// success bool as string
//var data = {'CustomProperty':'CustomValue'};
  Future updateUser(Map data) async {
    try {
      await appgainPlatform
          .invokeMethod(_updateUserWith, data)
          .then((result) {
            TextFieldAlertDialog().showAlertDialog(result.toString());
      });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }
  }

Geting Appgain user Id


  //Getting userID
//Output  : - callback with userID
  Future getUserId() async {
    try {
      await appgainPlatform
          .invokeMethod(_gettingUserId, '')
          .then((result) {
            TextFieldAlertDialog().showAlertDialog("userId=" + result.toString());
      });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }
  }

Notification Channels

This Tutorial aims to teach the user how to add user Notification and messaging preferences in channels such as SMS and Email


//MARK: enableReciveNotification

//enable (String)
//type (String) one of theses values ("appPush","sms","email")


// Output : -  callback with two parameter
  ///   success bool   as string
  ///   error
  Future enableReciveNotification() async {
    try {
      var data = {'enable':1,'type':'value'};
      await appgainPlatform
          .invokeMethod(_updateChannel, data)
          .then((result) {
              TextFieldAlertDialog().showAlertDialog(result.toString());
          });
    } on PlatformException catch (e) {
      TextFieldAlertDialog().showAlertDialog(e.toString());
    }
  }

Android Specific Instructions

  • go to https://firebase.google.com and log in with a Google Account.

  • At Firebase Website, in the right corner click on GO TO CONSOLE and click on Add Project , then give your Project a name.

  • Click on the settings icon next to Project Overview and then click on Project Settings

  • Click on GENERAL > Add Firebase to your Android app icon then fill in fields with :

  • Android package name : you can find it's value inside application Id value in app/build.gradle
  • Debug signing certificate SHA- 1 ,you can get it from :
  • Android studio > Gradle menu in (right toolbar of android studio)
  • Click on app menu
  • Click on android menu
  • Click on android on signingReport tas
  • Get SHA1 from run menu
  • Return to Firebase console click on REGISTER APP.
  • Download google-services.json file
  • Add google-services.json file to app folder in your android project files

  • Open the build.gradle file in the root directory of your Android Studio project.

  • Go to allprojects > repositories and configure the Maven repository address for the Appgain Core SDK.

java allprojects { repositories { maven { url "http://sdk.appgain.io/repository/maven-releases/" } google() jcenter() } }

  • Open the build.gradle directory in the app's root directory of your project.
  • Add following lines under dependencies.
   dependencies {
    implementation 'io.appgain.sdk:appgain-android:4.1.24'
    implementation 'com.google.firebase:firebase-messaging:20.2.0'
    implementation 'com.google.android.gms:play-services-ads-lite:18.1.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    implementation 'com.google.android.exoplayer:exoplayer:2.7.2'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
      annotationProcessor  'com.github.bumptech.glide:compiler:4.10.0'
  }


- also add this snippet to your app/build.gradle:

   buildTypes {
        release {
            minifyEnabled false
            shrinkResources false
        }
    }
  • also make sure that multiDex is enabled:
    android{
        multiDexEnabled = true
    }
  • and in the end of your file add the following line
   apply plugin: 'com.google.gms.google-services'
  • open your project/build.Gradle file and add following line under dependencies
 dependencies {  
    classpath 'com.google.gms:google-services:4.2.0'  
 }

Android Plugin Setup

  • Download and copy the following packages& files under java package which inside your project android package (android/app/src/main/java)
  • Download it from here io/appgain/flutter
  • if you are using proguard add this proguard rule to your proguard-rules.pro
keep class io.appgain.sdk.** {*;}
  • Then inside your launcher activity which is MainActivity class by default, add our plug-in integration
 @Override
 public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
     super.configureFlutterEngine(flutterEngine);
     flutterEngine.getPlugins().add(new AppgainFlutterPlugin());
 }
  • Add your application class to your android manifest.xml file
<application
 android:name=".io.appgain.flutter.controller.AppgainFlutterApplication"
  ..........
>

Finally , don't forget to refactor package name for APPGAIN classes from flutterAppgainTestApp to your main package name Ex : flutterAppgainTestApp.io.appgain.flutter.controller

Push Notification setup

firbase project settings


  • Go to Cloud Messaging tab and copy SenderID and Legacy server key

cloud settings


  • Open Appgain Dashboard
  • Go to Project Setting > Advanced Setting > Platforms
  • Navigate to Android push tab
  • enter your SenderID and Server key

Appgain Android Push settings

  • Create a new class that extends from AppgainPushReceiver class
class PushReceiver : AppgainPushReceiver() {
    override fun onReceive(context: Context?, receiveStatus: ReceiveStatus?, intent: Intent?) {

    }
}
  • Open manifest.xml file and add the following lines:
    <receiver
            android:name=".PushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>


        <service
            android:name="io.appgain.sdk.controller.AppgainMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
  • In your android application class, implement LifecycleObserver interface and add the follwing lines
class FlutterTestApp : FlutterApplication(), LifecycleObserver {
    override fun onCreate() {

        super.onCreate()
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this)
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Appgain.onAppBackgrounded()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Appgain.onAppForegrounded()
    }
}

For more info about all the methods in the Appgain SDK. please, refer to our native guides for android

iOS Specific Instructions

Installation

1- Add appgain pod to your generated project from flutter

pod 'Appgain'

2- Add

#import "Appgain.h"

To file -Bridging-Header.h

3- Add pod configuration for your pod installation inside generate file Debug.xcconfig

#include "Pods/Target Support Files/Pods-<!your-project-name!>/Pods-<!your-project-name!>.debug.xcconfig"

4- Add those inside Release.xcconfig

#include "Pods/Target Support Files/Pods-<!your-project-name!>/Pods-<!your-project-name!>.release.xcconfig"

#include "Pods/Target Support Files/Pods-<!your-project-name!>/Pods-<!your-project-name!>.profile.xcconfig"

5- Copy these file to your project from demo app.

AppDelegate+Flutter+Extension.swift

AppDelegate+Notifications+Extension.swift

6- How we start with this code Inside AppDelegate.swift

@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        let controller = self.window.rootViewController as! FlutterViewController

        //add and link Appgain SDK
        linkAppgainNativeCode(controller: controller)

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }  
}

Add Notification to your iOS target

Push Notification Setup

Add Appgain Rich Notification

Guide for native Rich Notification

1- Add target for rich notification

2- Add pod of rich push for two target

  pod 'Appgain-Rich'

3- Add pod configuration for your pod installation inside generate file Debug.xcconfig

#include "Pods/Target Support Files/Pods-<!your-content-extention-name!>/Pods-<!your-content-extention-name!>.debug.xcconfig"

#include "Pods/Target Support Files/Pods-<!your-service-extention-name!>/Pods-<!your-service-extention-name!>.debug.xcconfig"

4- Add those inside Release.xcconfig

//extension of service

#include "Pods/Target Support Files/Pods-<!your-service-extention-name!>/Pods-<!your-service-extention-name!>.release.xcconfig"

#include "Pods/Target Support Files/Pods-<!your-service-extention-name!>/Pods-<!your-service-extention-name!>.profile.xcconfig"

//extention of content

#include "Pods/Target Support Files/Pods-<!your-content-extention-name!>/Pods-<!your-content-extention-name!>.release.xcconfig"

#include "Pods/Target Support Files/Pods-<!your-content-extention-name!>/Pods-<!your-content-extention-name!>.profile.xcconfig"

For more info about all the methods in the Appgain SDK. please, refer to our native guides for ios

Finally You Can Use Appgain SDKTestApp to Test Appgain Features Before Integrate Your App with Appgain