Android SDK
Survey library to monetize your mobile app, provided by inBrain.ai.
Requirements
- System WebView >= 51.0.2704.90 (default for Android 7.0)
Installation
Integration is easiest with gradle dependency. In order to do that you need to add two pieces of code to your project.
First goes into root build.gradle file. You need to add jitpack.io repository into list of repositories for all projects like this:
allprojects {
repositories {
// other repositories here
maven { url 'https://jitpack.io' }
}
}
After that you just need to add the actual SDK dependency into build.gradle of the app module:
dependencies {
// other dependencies here
implementation 'com.github.dynata:inBrainSurveys-Android:3.1.0'
}
After re-syncing the project from gradle files you will be able to start using the inBrain SDK.
Get Started
Initialize the SDK
InBrain.getInstance().setInBrain(context, apiClientId, apiSecret, isS2S, userId);
context: Android contextapiClientId: The client ID obtained from your Publisher DashboardapiSecret: The client secret obtained from your Publisher DashboardisS2S: Is your app enabled with Server-to-Server(S2S) callbacks? Set to true if so, false if no server architecture.userId: The string value that uniquely identifies each user within your application (Example: an email, a username)
Note: This method must be called prior calling all the other methods.
User identifier
Set uniq identifier of the user within your application. If value not set (or empty) - deviceId will be used instead. This value is provided via S2S Callbacks as PanelistId. See more here: S2S Docs.
InBrain.getInstance().setUserId(userId);
userId: The string value that uniquely identifies each user within your application (Example: an email, a username)
InBrain Callbacks
To subscribe to events, add the following:
InBrain.getInstance().addCallback(callback);
Event callbacks are covered more in details in the Callbacks section.
Usage
Option #1: Use The Survey Wall
Simply show the survey wall and let the inBrain system handle everything else! Be sure to Setup your S2S Callbacks and fully configure your application here: Publisher Dashboard
For best user experience we recommend to check are the surveys available prior to giving the user an option to open the inBrain Survey Wall. DO NOT use this method when working with Native Surveys, as that does not take into account placement and categories filter options.
InBrain.getInstance().areSurveysAvailable(context, available -> {
if (!available) { return; }
InBrain.getInstance().openWall(context, WallOption.SURVEYS, new StartSurveysCallback() {
@Override
public void onSuccess() {
Log.d("MainActivity", "Successfully started inBrain");
}
@Override
public void onFail(String message) {
Log.e("MainActivity", "Failed to start inBrain: " + message);
}
});
});
Option #2: Use The Offers Wall
Simply show the offers wall and let the inBrain system handle everything else! Be sure to Setup your S2S Callbacks and fully configure your application here: Publisher Dashboard
InBrain.getInstance().openWall(context, WallOption.OFFERS, new StartSurveysCallback() {
@Override
public void onSuccess() {
Log.d("MainActivity", "Successfully started inBrain");
}
@Override
public void onFail(String message) {
Log.e("MainActivity", "Failed to start inBrain: " + message);
}
});
Option #3: Use Native Surveys
Native Surveys is similar to an API that can be used within our SDK. Fetch "Surveys" and receive a list of the top surveys for a single user based on their profiler data. inBrain handles collecting profiler data and matching users with the ideal surveys. When fetching surveys, we return a list with details about each survey opportunity such as Reward, Length of Interview, Rating, etc. You are responsible for displaying a representation (button, tile, etc.) for each survey natively within your app.
Important notes:
- Once the survey is completed - it becomes invalid and cannot be opened again;
- Please, take care about refreshing surveys with appropriate filter(s). We are proposing to fetch Native Surveys each time after InBrainWebView closed and some survey(s) completed;
- The same NativeSurvey may fit a few filters at the same time. If you are using a few filters - please, refresh the surveys for each filter where the survey presented;
- If you are using inBrain Wall as well - please take care about refreshing Native Surveys after some survey(s) completed. Use
surveysClosed(boolean byWebView, List<InBrainSurveyReward> rewards)method of InBrainCallback to detect InBrainWebView dismissal
Fetch Native Surveys
Without filter:
InBrain.getInstance().getNativeSurveys(surveyList -> {
// Display surveys to the user
Log.d("MainActivity", "Count of Native Surveys returned: " + surveyList.size());
});
With filter:
SurveyFilter filter = new SurveyFilter();
filter.placementId = YOUR_PLACEMENT_ID;
filter.includeCategories = yourIncCategories;
filter.excludeCategories = yourExcCategories;
InBrain.getInstance().getNativeSurveys(filter, surveyList -> {
// Display surveys to the user
Log.d("MainActivity", "Count of Native Surveys returned: " + surveyList.size());
});
filter: Optional parameter for filter surveys. Possible options:placementId (String): an optional placement identifier. These can be setup in your Publisher DashboardincludeCategories (List<SurveyCategory>): an optional list of categories. Providing one or more categories will limit surveys to those categories.excludeCategories (List<SurveyCategory>): an optional list of EXCLUDED categories. Providing one or more excluded categories will only return surveys that do NOT belong to these categories.
Open A Native Survey
When a user within your app selects a survey, you will then need to call showNativeSurveyWith along with the following survey data points. This will open the survey within a webview over your app.
InBrain.getInstance().showNativeSurveyWith(context, surveyId, searchId, offersEnabled, new StartSurveysCallback() {
@Override
public void onSuccess() {
Log.d("MainActivity", "Successfully started inBrain");
}
@Override
public void onFail(String message) {
Log.e("MainActivity", "Failed to start inBrain: " + message);
}
});
surveyId: id of the surveys to be shown;searchId: survey'ssearchId;offersEnabled: Specifies whether to enable Offers feature at the Wall or not.
Understanding Native Surveys
Native Survey is an object which represents survey and has the following properties:
| Property | Description |
|---|---|
id | Id of the survey and the value that should be used when passing parameter to showNativeSurvey() |
rank | A normalized value of 1-N where 1 is highest ranked survey and N is the lowest ranked survey |
time | An estimation of how many minutes will be required for the user to complete the survey |
value | Reward the user will earn by completing the survey. This value is in the currency type (points, coins, cents) you specified within the publisher dashboard and already takes into consideration the revenue share you've allocated to share with the user for a survey completion. |
isProfilerSurvey | Boolean value indicating whether the survey represents an inBrain Profiler survey |
currencySale | Boolean value indicating if the value of the survey is adjusted based on an active currency sale |
multiplier | The currency sale multiplier value applied to the survey value |
conversionLevel | Value that indicates the approximate conversion rate of the survey. See possible values here |
categories | Array of values indicating what categories this survey belongs to. See possible values here |
searchId | This value should be used when opening a native survey. It includes important encoded information related to placement and category filters |
Option #4: Use Native Offers
Native Offers is similar to an API that can be used within our SDK. Fetch "Offers" and receive a list of offers for a single user. When fetching offers, we return a list with details about each offer opportunity such as Reward, Goals, Promotions, etc. You are responsible for displaying a representation (button, tile, etc.) for each offer natively within your app.
Get Native Offers
InBrainOfferFilter filter = new InBrainOfferFilter(InBrainOfferType.DEFAULT, 20, 0);
InBrain.getInstance().getNativeOffers(filter, new GetNativeOffersCallback() {
@Override
public void onSuccess(List<InBrainNativeOffer> offers) {
// Cache offers and show them to the user
Log.d("MainActivity", "Count of Native Offers returned: " + offers.size());
}
@Override
public void onFailure(Throwable error) {
// Handle error depends on app logic
Log.e("MainActivity", "Failed to get offers: " + error.getMessage());
}
});
Kotlin example:
val filter = InBrainOfferFilter(type = InBrainOfferType.DEFAULT, limit = 20, offset = 0)
InBrain.getInstance().getNativeOffers(filter, object : GetNativeOffersCallback {
override fun onSuccess(offers: List<InBrainNativeOffer>) {
// Cache offers and show them to the user
Log.d("MainActivity", "Count of Native Offers returned: ${offers.size}")
}
override fun onFailure(error: Throwable) {
// Handle error depends on app logic
Log.e("MainActivity", "Failed to get offers: ${error.message}")
}
})
filter: Optional parameter for filter offers. Possible options:type (InBrainOfferType): Type of the offers to be returned (required). Possible values:InBrainOfferType.DEFAULT- returns default offersInBrainOfferType.FEATURED- returns featured offersInBrainOfferType.STARTED- returns started offers
limit (Int): Maximum amount of offers to be returned (optional, default: 10)offset (Int): Offset from the beginning of the list (optional, default: 0)- Important: When using
STARTEDtype, thelimitandoffsetparameters are ignored by the API
Start A Native Offer
When a user within your app clicks to start an offer, you will then need to call openOfferWithId along with the offer's id. This will send the user to the offer link within a webview over your app.
InBrain.getInstance().openOfferWithId(offerId, context, new OpenOfferCallback() {
@Override
public void onSuccess() {
Log.d("MainActivity", "Offer opened successfully");
}
@Override
public void onFailure(Throwable error) {
Log.e("MainActivity", "Failed to open offer: " + error.getMessage());
}
});
Kotlin example:
InBrain.getInstance().openOfferWithId(offerId, context, object : OpenOfferCallback {
override fun onSuccess() {
Log.d("MainActivity", "Offer opened successfully")
}
override fun onFailure(error: Throwable) {
Log.e("MainActivity", "Failed to open offer: ${error.message}")
}
})
offerId: id of the offer to be showncontext: Android context
Understanding Native Offers
Native Offer is an object which represents an offer and has the following properties:
| Property | Description |
|---|---|
id | Id of the offer and the value that should be used when passing parameter to openOfferWithId() |
title | The title of the offer |
reward | Total reward the user can earn by completing the offer (Double) |
rewardString | Formatted string representation of the reward |
featuredRank | The featured rank of the offer in the featured offers list. Always -1 for non-featured offers |
thumbnailUrl | Optional URL to the offer's thumbnail image |
heroImageUrl | Optional URL to the offer's hero/banner image |
description | Optional list of strings describing the offer |
categories | Optional list of category names this offer belongs to |
promotion | Optional promotion object if the offer has an active promotion (see InBrainOfferPromotion) |
standardGoals | Optional list of standard goals for this offer (see InBrainOfferGoal) |
purchaseGoals | Optional list of purchase-based goals for this offer (see InBrainOfferGoal) |
InBrainOfferPromotion
Promotion details for an offer with an active promotion:
| Property | Description |
|---|---|
multiplier | The promotion multiplier applied to the reward (Double) |
originalReward | The original reward value before promotion (Double) |
originalRewardString | Formatted string representation of the original reward |
InBrainOfferGoal
Goal details for an offer:
| Property | Description |
|---|---|
id | Id of the goal |
title | The title of the goal |
description | Description of what needs to be completed |
reward | Reward for completing this goal (Double) |
rewardString | Formatted string representation of the reward |
isCompleted | Boolean indicating if the goal has been completed |
sortOrder | The display order of the goal. Always -1 if not specified |
attributionWindowMinutes | The attribution window in minutes for not started offers. Always -1 for started offers |
completeBy | Optional deadline to complete this goal in UTC timezone for started offers. Always null for not started offers |
promotion | Optional promotion object if the goal has an active promotion (see InBrainOfferPromotion) |
Advanced Usage
Custom Tracking Data & Demographic Data
The inBrain SDK provides additional functions (setDataOptions(), getDataOptions(), setSessionId(), getSessionId()) which allow you to do two things:
Provide demographic data
Provide demographic data to provide an even more seamless on-boarding of your users into the inBrain experience. For example, you can pass gender and age with the following:
HashMap<String, String> dataOptions = new HashMap<>();
dataOptions.put("gender", "female");
dataOptions.put("age", "26");
InBrain.getInstance().setDataOptions(dataOptions);
Provide tracking data
Value to track each user session. This value is provided via S2S Callbacks as SessionId. See more here: S2S Docs
String trackingData = "{ someCustomField: 'tracking_data' }";
InBrain.getInstance().setSessionId(trackingData);
Please, note: The above configuration should be done before showing the surveys, or it will have no effect.
Currency Sale
The SDK provides an option to get active currency sale:
InBrain.getInstance().getCurrencySale(new GetCurrencySaleCallback() {
@Override
public void onSuccess(CurrencySale sale) {
// Show the info to the user
}
@Override
public void onFailure(Throwable error) {
// Handle the error
}
});
Customize UI
InBrainSurveys provides to customize some UI elements of InBrainWebView. In order to do that - call these functions prior to showing InBrainWebView:
Toolbar Configuration
ToolBarConfig toolBarConfig = new ToolBarConfig();
toolBarConfig.setTitle(getString(R.string.app_name)); // set title
boolean useResourceId = false;
if (useResourceId) {
toolBarConfig.setToolbarColorResId(R.color.colorAccent) // set toolbar color with status bar
.setBackButtonColorResId(android.R.color.white) // set icon color
.setTitleColorResId(android.R.color.white); // set toolbar text
} else {
toolBarConfig.setToolbarColor(getResources().getColor(R.color.colorAccent))
.setBackButtonColor(getResources().getColor(android.R.color.white))
.setTitleColor(getResources().getColor(android.R.color.white));
}
toolBarConfig.setElevationEnabled(false);
InBrain.getInstance().setToolbarConfig(toolBarConfig);
Available methods:
Set toolbar color:
toolBarConfig.setToolbarColor(getResources().getColor(R.color.your_color));
Also you may pass color's resource id:
toolBarConfig.setToolbarColorResId(R.color.your_color);
Title:
toolBarConfig.setToolbarTitle(getString(R.string.app_name));
If you want to leave toolbar's text empty, just pass empty String to it:
toolBarConfig.setToolbarTitle("");
Title text's color:
toolBarConfig.setTitleColor(getResources().getColor(R.color.your_color));
Also you may pass color's resource id:
toolBarConfig.setTitleColorResId(R.color.your_color);
Back icon's color:
toolBarConfig.setBackButtonColor(getResources().getColor(R.color.your_color));
Also you may pass color's resource id:
toolBarConfig.setBackButtonColorResId(R.color.your_color);
If you want to enable elevation for toolbar, use:
toolBarConfig.setElevationEnabled(true);
Finally, set toolBarConfig to the inBrain:
InBrain.getInstance().setToolbarConfig(toolBarConfig);
Status Bar Configuration
StatusBarConfig statusBarConfig = new StatusBarConfig();
if (useResourceId) {
statusBarConfig.setStatusBarColorResId(android.R.color.white)
.setStatusBarIconsLight(false);
} else {
statusBarConfig.setStatusBarColor(getResources().getColor(android.R.color.white))
.setStatusBarIconsLight(false);
}
InBrain.getInstance().setStatusBarConfig(statusBarConfig);
Available methods:
Set status bar color:
statusBarConfig.setStatusBarColor(getResources().getColor(R.color.your_color));
Also you may pass color's resource id:
statusBarConfig.setStatusBarColorResId(R.color.your_color);
By default, status bar icons' color will be white. If you need to use black status bar icons:
statusBarConfig.setStatusBarIconsLight(false);
Callbacks
In app callbacks are delegate functions that are executed upon specific events and allow you to intercept those events. Below is an example of setting up event callbacks:
private final InBrainCallback callback = new InBrainCallback() {
/**
Called upon dismissal of inBrainWebView.
If you are using Native Surveys - please, ensure the surveys reloaded after some survey(s) completed.
@param byWebView: **true** means closed by WebView's command; **false** - closed by user;
@param rewards: **NOTE:** At the moment only **first** Native Survey reward is delivered.
That means if the user completes a Native Survey, proceed to the inBrain Wall and complete one more survey - only first
reward will be delivered. In case of the inBrain Wall usage only - no rewards will be delivered.
*/
@Override
public void surveysClosed(boolean byWebView, List<InBrainSurveyReward> rewards) {
// Handle the event - refresh surveys/offers, process rewards, etc.
}
};
If you added a callback in onCreate, you should remove your callback in onDestroy method of the activity like this:
@Override
protected void onDestroy() {
InBrain.getInstance().removeCallback(callback); // unsubscribe from events
super.onDestroy();
}
Don't forget to remove the callbacks, otherwise it can cause a memory leak!
Check For Rewards in App
The typical inBrain integration flow is that your app would receive reward events to your server via Server-to-Server callbacks as opposed to checking for earned rewards within the app experience. In the case that you DO want to check for rewards earned during the inBrain experience, you can utilize the following:
InBrain.getInstance().getRewards(new GetRewardsCallback() {
@Override
public boolean handleRewards(List<Reward> rewards) {
// Process rewards, display to users, etc.
return true; // must return true! failure to return true may result in receiving duplicate rewards within this function
}
@Override
public void onFailToLoadRewards(Throwable t) {
// Handle the fail, where t is a throwable that might help to investigate the error.
}
});
Note: We highly recommend using Server-to-Server Callbacks for receiving and processing rewards.
Check if Surveys are Available
The inBrain SDK provides functionality to check if surveys are available for a user. For best user experience we recommend to check surveys availability prior to call openWall(). This should be done after the initial inBrain configuration.
InBrain.getInstance().areSurveysAvailable(context, new SurveysAvailableCallback() {
@Override
public void onSurveysAvailable(final boolean available) {
Log.d("MainActivity", "Surveys available: " + available);
}
});
Available types and interfaces
Native Survey
Native Survey is an object which represents survey and has the following properties:
| Property | Description |
|---|---|
id | Id of the survey and the value that should be used when passing parameter to showNativeSurvey() |
rank | A normalized value of 1-N where 1 is highest ranked survey and N is the lowest ranked survey |
time | An estimation of how many minutes will be required for the user to complete the survey |
value | Reward the user will earn by completing the survey. This value is in the currency type (points, coins, cents) you specified within the publisher dashboard and already takes into consideration the revenue share you've allocated to share with the user for a survey completion. |
isProfilerSurvey | Boolean value indicating whether the survey represents an inBrain Profiler survey |
currencySale | Boolean value indicating if the value of the survey is adjusted based on an active currency sale |
multiplier | The currency sale multiplier value applied to the survey value |
conversionLevel | Value that indicates the approximate conversion rate of the survey. See possible values here |
categories | Array of values indicating what categories this survey belongs to. See possible values here |
searchId | This value should be used when opening a native survey. It includes important encoded information related to placement and category filters |
Native Offer
Native Offer is an object which represents an offer and has the following properties:
| Property | Description |
|---|---|
id | Id of the offer and the value that should be used when passing parameter to openOfferWithId() |
title | The title of the offer |
reward | Total reward the user can earn by completing the offer (Double) |
rewardString | Formatted string representation of the reward |
featuredRank | The featured rank of the offer in the featured offers list. Always -1 for non-featured offers |
thumbnailUrl | Optional URL to the offer's thumbnail image |
heroImageUrl | Optional URL to the offer's hero/banner image |
description | Optional list of strings describing the offer |
categories | Optional list of category names this offer belongs to |
promotion | Optional promotion object if the offer has an active promotion (see InBrainOfferPromotion) |
standardGoals | Optional list of standard goals for this offer (see InBrainOfferGoal) |
purchaseGoals | Optional list of purchase-based goals for this offer (see InBrainOfferGoal) |
InBrainOfferPromotion
Promotion details for an offer with an active promotion:
| Property | Description |
|---|---|
multiplier | The promotion multiplier applied to the reward (Double) |
originalReward | The original reward value before promotion (Double) |
originalRewardString | Formatted string representation of the original reward |
InBrainOfferGoal
Goal details for an offer:
| Property | Description |
|---|---|
id | Id of the goal |
title | The title of the goal |
description | Description of what needs to be completed |
reward | Reward for completing this goal (Double) |
rewardString | Formatted string representation of the reward |
isCompleted | Boolean indicating if the goal has been completed |
sortOrder | The display order of the goal. Always -1 if not specified |
attributionWindowMinutes | The attribution window in minutes for not started offers. Always -1 for started offers |
completeBy | Optional deadline to complete this goal in UTC timezone for started offers. Always null for not started offers |
promotion | Optional promotion object if the goal has an active promotion (see InBrainOfferPromotion) |
InBrainOfferFilter
Filter object for fetching Native Offers:
| Property | Description |
|---|---|
type | Type of the offers to be returned (InBrainOfferType: DEFAULT, FEATURED, or STARTED) |
limit | Maximum amount of offers to be returned (default: 10) |
offset | Offset from the beginning of the list (default: 0) |
Survey Category
The survey may belong to one or a few categories, as well as may have no categories at all. The list of all possible categories may be found bellow:
- Automotive
- Beverages Alcoholic
- Beverages Non Alcoholic
- Business
- Children & Parenting
- Coalition Loyalty Programs
- Destinations & Tourism
- Education
- Electronics, Computer Software
- Entertainment And Leisure
- Finance, Banking, Investing & Insurance
- Food
- Gambling, Lottery
- Government & Politics
- HealthCare
- Home
- Media & Publishing
- Personal Care
- Restaurants
- Sensitive & Explicit Content
- Smoking & Tobacco
- Social Research
- Sports Recreation Fitness
- Telecommunications
- Transportation
- Travel - Airlines
- Travel - Hotels
- Travel - Services, Agency, Booking
- Credit Cards
- Video Games
- Fashion & Clothing - Other
- Fashion & Clothing - Department Store
Conversion Level
The Conversion Level buckets indicate how the survey has been performing platform-wide at inBrain, not necessarily how well the survey will perform for the user its shown to. Its recommended to use these tags only to portray a unique UI. Possible values are:
- New Survey;
- Very Poor Conversion
- Poor Conversion;
- Fair Conversion;
- Good Conversion;
- Very Good Conversion;
- Excellent Conversion.