@benshi.ai/react-native-bsh-core
TypeScript icon, indicating that this package has built-in type declarations

1.1.4 • Public • Published

Benshi React Native (Android) SDK Setup

This documentation covers the steps to integrating SDK in your react native (android) apps. We’ll also discuss a few fundamentals of how the dashboard works in tandem with your app usage to view your users and engage them with contextually personalized messages.

There are two types of data we collect from the partner's side:

  1. content data (static content / items in the app)
  2. event data (event names, event details)

Content data are static data of certain content (e.g. video, audio, a product, etc.). Event data is time-series data generated by the user.

Getting Started

In order to create ease for partners, we have divided the SDK into multiple modules. Each module represents a specific app niche that partners can use based on their app category.

A list of these modules are:

  1. Core

  2. E-commerce

  3. E-Learning

  4. Loyalty

  5. Payments

In order to use the SDK, Core is mandatory to include as it contains the elements regarding the basic app navigation and workflow including nudges. Moreover, all the modules require the core to be integrated in order to successfully log the events.

The easiest way to integrate Benshi react native (android) SDK in your project is using an NPM package. Add dependencies of react-native SDK in the dependencies section of your package.json of your project and Android Lifecycle Components in the app/build.gradle file.

"dependencies": {
    "@benshi.ai/react-native-bsh-core": "<version_number>"
  },

for version_number please head to npm package.

After including the above, Open terminal/shell and go to your project directory, and run:

npm install

This will install the core npm package in the node modules of your project. Now you need to link this module with your android app, for this in the same terminal in your project directory run:

react-native link @benshi.ai/react-native-bsh-core

This will link your newly added module with your android app and you can also see the link in your android settings.gradle file.

As SDK requires app events to auto manage the logging of user sessions you also need to include android lifecycle dependency in your android app/build.gradle file. To add the dependency, open your android folder in Android Studio and open the app-level build.gradle file. now in your dependencies add the following:

dependencies {

    //LifecycleComponents
    implementation 'androidx.lifecycle:lifecycle-process:2.3.1'
    implementation project(path: ':@benshi.ai_react-native-bsh-core')

}

Lifecycle components are required, if you already have them in your project you may skip them.

Initialization

Create an Application class in your project and include LifecycleEventObserver Components. Initialize Android SDK with your SDK Token from onCreate callback of your Application class as shown below.

public class MainApplication extends Application implements ReactApplication, LifecycleEventObserver {

    @Override
  public void onCreate() {
    super.onCreate();

      // to observe Application lifecycle events
      ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

  }

    /*
        In onStateChanged() function include the following function to auto-track events related to app and activity lifecycle.
    */
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        BsLogCore.benshiInit(this, event);
    }

Benshi Android SDK requires an SDK key in order to log events. To do so, you need to create an SDK key from the Benshi Platform and pass it to the SDK using the app's Manifest file as meta-data like below:

<meta-data android:name="ai.benshi.android.sdk.APPLICATION_KEY"
            android:value="<SDK_KEY_HERE>" />

Benshi Android SDK also allows you to update track events after the user’s usage session is over. SDK sends the events whenever the app goes into the background. This helps in not overloading the user’s phone while in use. SDK handles the events even in offline mode and ensures that they get uploaded to the portal whenever the user connects to the internet. SDK also auto logs the App Open, close, and background events so, you don't have to implement those.

Don't forget to include android:name=".MyApplication" in your manifest's application tag.

Android SDK - Core - Event Tracking

Benshi Android SDK automatically starts tracking user data (e.g., Upload/download speed, OS version, device IDs) and engagement with the basic setup above. This data can be stored on the device and uploaded in batches to reduce network and power usage, and to increase the likelihood of successful uploads while you can also upload the events as soon as they happen. The upload is done when the user device session ends. SDK also starts tracking user sessions with this basic setup.

Each event can further be understood in the context of its attributes which includes details like time, upload/download speed, device details, locale, online/offline usage, screen time, interactions, and so on. This enables you to gain in-depth insights into user interactions across your app. You can also leverage this data to segment users, personalize messages and configure campaign targeting.

Let’s take a look at the general structure of the attributes sent using that SDK:

Property Name Reported on Portal Description
User Id u_id User Id assigned in your Database, if you don’t have any signup/login process SDK defaults that to deviceID.
Device Id d_id User’s Device ID to uniquely recognize.
OS os The current OS they are using. It is specified in {os.Name (os.Version)} e.g. android (30) Having the device OS and version help us to deliver content better presentable on their device.
SDK Version sdk Current SDK version you are using.
Content Block block Current content block name the log is being called.
Online Status ol Tracks if the device was online or not when the event was recorded.
Timestamp ts Track the timestamp of the event in RFC 3339 format.
Upload Speed up Track the upload speed of the device when the event was recorded.
Download Speed down Track the download speed of the device when the event was recorded.
Event Type type Type of event being tracked, use EventType class predefined events.
Properties props Properties of the event being tracked. SDK provides predefined property models for you to integrate with ease. You can also track custom events too.

For example, if a user needs to click on a product to view its details, then it is advisable to track this action as the event, product viewed as it brings them a step closer to making a purchase.

To log CoreEvents you need to import BshCore main class and contents to support different actions:

import BshCore from '@benshi.ai/react-native-bsh-core';

Here BshCore is the main class for all the core-related events to help you implement logs in a functional approach. while rest are content classes to help you with actions for different logs. You can also pass strings instead of these content values but the params should be the same as provided in contents or else the log will not be triggered and an exception will be thrown by the SDK. BshCore class contains a list of functions in the core module and every function has 2 extra params to help you, you can include them in the parent functions, one is meta which you can use to pass data you want to the SDK but remember to pass it in as key-value pair and convert that to JSON string so that it may be parsed with the rest of the SDK content. the last parm is the updateImmediately boolean which helps you to send a specific log as soon as it happens as by default SDK logs the events at the end of the session in a batch.

SDK events are divided into 2 main categories: User Events and System Events.

Tracking User Events

SDK automatically starts detecting the users across your platforms as soon as they're integrated. These visitors are classified as Unknown Users and Known Users.

Let's walk you through this:

Unknown Users

Each time a new user uses your app, they are tracked as anonymous users in your dashboard and an Unknown User Profile is created for them. The Android SDK automatically assigns them a unique ID (based on their device ID) and starts populating their user profile with all their data (System Events).

Known Users (Identity Events)

As and when the users share details that help you identify them in your platform, you can assign them a unique ID (Your Platform-based UserId) to track them as Known Users. This user is now stored in our database as the ‘Identified/Registered’ ones. A new user profile is created for them that contains all their data from the previous anonymous user profiles, too merged with the new account.

Implementation

To Log identity events that involve events regarding the user of the app such as register, login, or log out you can use Identity log events that are divided into 3 different types. For convenience, you can use IdentityAction.{action name} in the log function. examples are:

  • IdentifyAction.register for new user (sign up)
  • IdentityAction.login for login (sign in)
  • IdentityAction.logout for logout (sign out)

Identity events are used to log user-related events that represent user register events, user login events, and user logout events. SDK will store the userId provided in the identity events and log the remaining events with that userId. So you don't have to provide the userId again. In case of a logout event, SDK will auto-erase all of the stored data including the userId. Identity events require 2 main params:

@param userId is the user id that is using the app, userId should be the id from your platform that is assigned to the user. @param identityAction enum is the identity Action that defines whether the user is logging in or a new user or logging out.

/*
You can log the register event as:
*/
let identityProperties = {
  user_id: "testUserIdRn",
  identity_action: IdentityAction.Register,
  user_properties: null
};


/*
You can Log the sign-in of the user, use the below, you don't need to call the login on the splash screen or every time the user opens the app.
*/
let identityProperties = {
  user_id: "testUserIdRn",
  identity_action: IdentityAction.Login,
  user_properties: null
};

/**
You can also set using the Logout event as:
**/
let identityProperties = {
  user_id: "testUserIdRn",
  identity_action: IdentityAction.Logout,
  user_properties: null
};


/**
 * To log the Identity event you need to call the following function:
 **/

BshCore.logIdentityEvent(identityProperties)

appUserId is required to identify the user based on the userID. You only need to provide this Id once and afterward, the SDK will be responsible for storing and passing the userID with log events. One important thing to note here is that calling the logout action will remove any data stored by the SDK including the userID but only after successfully uploading the existing data to the backend.

@param user_properties can be used to send the user properties which are logging in. It will include information about the user which includes:

name,
country,
region_state,
city,
workplace,
profession,
zipcode,
language,
experience,
education_level,
organization,

You can also pass null for user_properties if you don't have the properties at the time of login.

Tracking System Events

We have several predefined actions that users can perform while interacting with your app. These actions are referred to as System Events that help in tracking elements on your app with user interaction. Some of these events are automated so that you don’t have to spend time integrating them.

Here's a list of System Events that can be tracked using the core module:

Event Name Calling in SDK Description
Page EventType.page Track screen/activity changes and session timing. (Auto Tracked)
Media EventType.media Track how your users interact with media to offer better
Search EventType.search Track how search responds on user queries.
Rate EventType.rate Track how user rates to certain elements in the app.
Track EventType.track Track how your users interact with elements inside the app.

Usage for the above-mentioned events is given below:

Page Event

To Log page/screen change events.

By default, SDK auto listens for Activity changes in the app along with session timings that implicates how to log a user spends on an activity, but you can also log any specific event you want to track using the below approach:

  • @param content_block enum is for the module the page is used in, ECommerce, ELearning, ...
  • @param page_path is for the page path, where the page/screen is inside the code packages.
  • @param page_title is the page name, the name of the class.
  • @param duration is the duration (in seconds, integer) the user spent on that page, it is ideal to log this event when the user moves to the next page so that you can track the time user spent on the page.
let pageProperties = {
  content_block: ContentBlock.ELearning,
  page_path: "test Page Path",
  page_title: "test page name",
  duration: 3 // 5 is the number of seconds user spent on that activity/screen/component.
}

BshCore.logPageEvent(pageProperties)

Media Events

Media events can be used to log events regarding media, for logging the user interaction with the media controls. For example video, image, and audio. you can track different interaction events based on your implementation like when the user plays or pauses the video or audio, if they seek the video or audio to a certain time frame or if they watched the video or finished listening to the audio. Params details are as below:

  • @param content_block enum is for the module the media is used in, ECommerce, ELearning, ...
  • @param media_id is for the mediaId used in your system, should be a string.
  • @param media_type enum is for the media type that if it is a video, audio, or image.
  • @param media_action enum is for the actions performed on the media, it includes play, pause, seek and finish. For Image, media type the default media action is a play event that represents an image open event. The same will be used if the user swipes in a fullscreen image browser.
  • @param time is the timeframe in milliseconds for the video and audio, this is the actual time of the media when the event is triggered.
  • @param media_data is to send the media properties in question.
let mediaProperties = {
  content_block: ContentBlock.ECommerce,
  media_id: "testRNMediaId",
  media_type: MediaType.Video,
  media_action: MediaAction.Play,
  time: 3000, // currentSeekTime is the timeInMillis for the video/audio current timeframe.
  media_catalog: MediaCatalogModel
}

BshCore.logMediaEvent(mediaProperties) 

MediaType is required to define the type of media being interacted with. It is required to define if the media interacted with is audio, is a video, or an image. SDK provides enum MediaType to use for media types.

Image // for image media type
Video // for video media type
Audio // for audio media type

MediaAction is required to log the interaction action with the media. SDK provides enum MediaAction to support mediaActions and are defined in 4 different actions.

Play // to log the start of the media like video or audio or even open the image.
Pause // to log the pause event for the audio and video media types.
Seek // to log the seek event when the user interacts with the seek bar of the video.
Finish // to log the finish event of the media.

You can also use MediaCatalogModel to also log the media catalog for media meta-data which can include the video/audio name, description if any, length of the video along with the resolution and language the video is in. Media Model contains the following values:

name, // string - Optional
description, // string - Optional
length, // int - Required
resolution, // string - Optional
language // string - Optional - Language Code enum provided

Note: You only need to provide the media model on any one one, preferably when you trigger the play action. For images you are not required to log the media model.

Impression Listener

Benshi React native SDk currently supports RecyclerListViewScreen for the impression listener as it helps in recycling the views and improving performance. To start with the implementation,, you need to first map your list in the format required by the SDK.

var contentList = YOUR_LIST.map((video, index) => ({
        item_properties: {
            id: video.id,
            type: MediaType.Video,
            time: video.currentSeekTime
        },
        catalog_properties: {
            name: video.title,
            description: video.description,
            length: video.totalDuration,
            resolution: "720p",
            language: LanguageCode.English
          }
      }));

then on your _lonVisibleIndicesChanged call the impression listener and pass the contentList:

const _lonVisibleIndicesChanged = (all, now, notNow) => {
        BshCore.logMediaImpressionEvent(
                "collectionId",now,
                contentList, "searchId",
            );
      }

    return (
      <View style={styles.container}>
            <RecyclerListView rowRenderer={_renderRow} dataProvider={dataProvider}
                              layoutProvider={_layoutProvider}
                              onVisibleIndicesChanged={_lonVisibleIndicesChanged}
                              />
        </View>
    );

Impression listener will auto track the elements shown on the screen and log the impression events and also for the redundant scroll impressions.

Search Events

You can use search events to track how search returns results based on user queries and what items users are searching for. It supports all the modules available by benshi i.e. general, e-learning, e-commerce, etc. You also need to log the Ids in the form of a string list to log what results are returned by the search and in case of no result found, you can log with an empty list. Search also supports filters if any applied to the search by the user which is supported in the app. You can provide these filters in the form of hashMap formatted as <string, string>

  • @param content_block enum is for the module the search is used in, ECommerce, ELearning, ...
  • @param query is for the search query that the user is searching for.
  • @param results_list is the list of results returned in the search, can be an empty list in case of no results returned.
  • @param filters is the filter applied on search, filters should be mapped as a hashmap data type with <string, string> format. in case the search does not offer any filters you can also send null in place of the filter param.
  • @param page_number is the current page the user is currently on.
  • @param is_new_search is a boolean to notify if the search performed is new or an old element.
let searchProperties = {
  content_block: ContentBlock.Loyalty, // content block for the search used in.
  query: "Hello World",  // query search for
  results_list: Array<SearchItemModel>, // string  array for the result ids
  filters: Map<string, any>, //
  page_number: 1, // current page number of the page number user is currently on
  is_new_search: true // notifies if it is a new search or change in page.
}

BshCore.logSearchEvent(searchProperties, (searchId)=>{
console.log(searchId); // search log also returns a unique id back to be used ion the search impression listeners.
})

SearchItemModel have following elements:

id: string, // id of the item
type: SearchItemType // type of the item provided by enum SearchItemType


// Where SearchItemType has following elements
Blood = "blood",
Oxygen = "oxygen",
Drug = "drug",
MedicalEquipment = "medical_equipment",
Electronics = "electronics",
Clothing = "clothing",
Book = "book",
Misc = "misc"

Rate Event

To log user interactions with rate elements inside the app. Can be used with interactions on rating for app itself, order, course or an exam.

  • @param content_block enum is for the module the rate is used in, ECommerce, ELearning, ... default is core.
  • @param rateValue is for the providing the value for the rate. Should be in between 0 to 5, if there are more elements like 0 to 10, make sure to divide the value by 2.
  • @param type is for the providing the type of type being rated. By default SDK provides enum values for the rate type to log the events base don specific types but you can also use string values as well. Below is the function for logging rate type using string.Remember to use the same strings as provided in the enums or else the event will be discarded.
  • @param subjectId is required to set the subject Id for the item being rated. It is required in all cases, if the app is rated then provide the application id.
let rateProperties = {
  content_block: ContentBlock.ECommerce,
  rate_value: 4.5, // range 0 to 5 (both inclusive)
  type: RateType,
  subject_id: string,
}

BshCore.logRateEvent(rateProperties)

RateType is for providing the types of elements you can log:

Order // for rating the experience on placing an order.
Media // for rating the experience on a media watched.
Exam // for rating the experience on attempting an exam.
App // for rating the experience on using the whole app.

Track Events

To log user interactions with custom components inside the app. Track events are required to log events related to UI elements, viewing a list, viewing an item, and also if the user taps on an external link. There are 3 types of track at the moment which included view list, view item, and opening an external link

  • @param track_action is for providing the type of track being logged. For Track events, you need to set the track type to differentiate among multiple track types. TrackType can be viewing a list of elements, tapping an item from the list to view more details on that but in such case passing the item id is required to log the event.
  • @param item_id is required to set the item Id for the item being viewed. It is required if the track type is view_item. For others, you may skip this.
let trackObject = {
  track_action: TrackAction.ViewItem,
  item_id: "itemId"
};

BshCore.logTrackEvent(trackObject)

TrackType is for providing the type of track being logged. For Track events, you need to set the track type to differentiate among multiple track types. TrackType can be viewing a list of elements, tapping an item from the list to view more details on that but in such case passing the item id is required to log the event.

ViewList // for viewing a list of elements
ViewItem // for viewing a specific element
ExternalLink // for opening an external link to provide more information

For implementation, you can also view the demo app.

Android SDK - Nudge

With Nudges, you can utilize experiment-based data-driven insights and predictions for individual behaviors towards shaping strategies for collective behaviors. Nudges help you to interact with your users. You can use nudge to send push notifications, in-app messages or use other methods to interact with your users.

App publishers can send them at any time; even if the recipients aren’t currently engaging with the app or using their devices. You can start sending Push Notifications to your users via the Benshi platform after initializing the SDK. SDK will listen for the nudges on its own and also log the user behavior based on the nudge Id that if the user opened the nudge or discarded that. in order to implement Call To Actions for nudges, SDK provides callback functions to open elements in the app.

BshCore.getNudgeResponse((cta_type, nudge_resource_type, nudge_resource_id)=>{
    console.log("Notification CTA Type: "+cta_type);
    console.log("Notification CTA resource Type: "+nudge_resource_type);
    console.log("Notification CTA resource Id: "+nudge_resource_id);
  })
  • cta_type is the type of the nudge Call to Action, so far we have 2 types: redirect and add-to-cart
  • nudge_resource_type is type of the resource to be opened by the nudge, drug and media
  • nudge_resource_id is the id of the resource to be opened by the nudge. You can use the is to open into your app.

Guidelines

  • Including lifecycle components is required in order to use the SDK as SDK requires lifecycle components to listen for app events regarding app sessions and app moving to the background.
  • Anything you include in the meta will be sent to the backend and be visible in the log monitoring section, but it will not be processed.
  • Custom Event Attributes can be of these data types: String, Number, Boolean, Date, List, Map.
  • Make sure to include your SDK key in the manifest of your Android App so that SDK can have that while initialization or else it would through an IllegalAccessException.
  • Make sure to initialize the SDK in the Application class or else if you trigger SDK events without that it will through RuntimeException.
  • updateImmediately is an optional param, by default its value is true. You can decide for each event if it needs to be updated immediately, or it can wait until the end of the app session.
  • Please ensure consistent usage of the names of Custom Events in meta and their Custom Attributes across all your apps (Android, iOS) and website.
  • Please use the same name conventions as provided by the enums if you choose to pass strings as values or else the event will be discarded and an IllegalArgumentException will be thrown.
  • Nudges may not be delivered to apps which were put into background restriction by the user (such as via: Setting -> Apps and Notification -> [app-name] -> Battery). Once your app is removed from background restriction, new messages to the app will be delivered as before. In order to prevent lost messages and other background restriction impacts, make sure to avoid bad behaviors listed by the Android vitals effort. These behaviors could lead to the Android device recommending to the user that your app be background restricted. Your app can check if it is background restricted using: isBackgroundRestricted().
  • In cases where the user restricted the app to show push notifications for the whole app or blocked the benshi notification channel, the SDK will log blockevent for that nudge.

Please feel free to drop in a few lines at hello@benshi.ai in case you have any further queries. We're always just an email away!

Package Sidebar

Install

npm i @benshi.ai/react-native-bsh-core

Weekly Downloads

0

Version

1.1.4

License

none

Unpacked Size

528 kB

Total Files

69

Last publish

Collaborators

  • moizh
  • aecostas
  • sergiobenshi
  • sergiocarracedo
  • dxe.tang