Get started with the SDK

This article provides steps to include the SDK in your Android app's code so that your app can initialize the SDK and start using the SDK's features.

📘

Wait. Are you ready for this part?

We hope that you could set up the SDK in your app's project. If not, then we suggest that you set up the SDK in your project and then come back here to include it in your code.

We'll wait. Take your time. No pressure. :relaxed:

Initialize the SDK

To get started, the host app should initialize the blueshift sdk with a valid configuration.

Mandatory configurations

To initialize the SDK with the minimum requirements, add the following code to your app's Application file's onCreate() method.

Following are the minimum requirements for the SDK to get initialized.

  • App icon: The app icon resource id is required to show the icon on the push notification if not explicitly provided.
  • Event API key: This value is required to authenticate the events. You could find it here in the dashboard.
Configuration configuration = new Configuration();

// == Mandatory Settings ==
configuration.setAppIcon(R.mipmap.ic_launcher);
configuration.setApiKey("BLUESHIFT_EVENT_API_KEY");

Blueshift.getInstance(this).initialize(configuration);

🚧

API key

Ensure that you set the API key before proceeding. The integration fails if you don't specify the API key here.

📘

Application file? Huh?

When you create a project in the Android Studio for your app, you define the application file in the AndroidManifest.xml file of the project. When the app is built, the code from this file is the first component that gets started when a user runs your app on a device. For example, in the sample Blueshift Reads Android app that we provide for reference, you can see the AndroidManifest.xml file. In this file, you can see that the application class is mapped to the ReadsApplication.java file.

In this example, the onCreate() function resides in the ReadsApplication.java file.

Optional configurations

Following are optional configs. If you are going to use the SDK with only push and events (with default settings), you may skip to the next section. Curious minds can read ahead.

Push notification

The push notifications are enabled by default. But if the host app does not want to display push notifications from blueshift, then you could turn off the push notifications using the below method.

configuration.setPushEnabled(false);

🚧

This is purely a client-side setting. The blueshift server won't know that push is disabled if you turn it off using this method. To fully opt-out from the push, please refer to this document.

Push notification style

The SDK lets you customize the style of the notification by changing the icons and color.

// Provide appropriate icon resources to change the big and small icons.
// Default: App icon.
configuration.setLargeIconResId(R.drawable.notification_big_icon);
configuration.setSmallIconResId(R.drawable.notification_small_icon);

// The color of notification. This requires Android 21 or higher.
// Default: System default.
int color = ContextCompat.getColor(getApplicationContext(), R.color.notification_color);
configuration.setNotificationColor(color);

// The theme for Dialog type notifications. (Deprecated.)
// Default: System default.
configuration.setDialogTheme(R.style.dialog_theme);

Push notification channel (Android 8 or higher)

Android Oreo onwards, the notification framework requires a notification channel to be defined when you create a notification. The Android OS will skip the notification if a channel is not provided.

The below methods will let you provide a default value for notification channel id, name, and description. These values will be used when the push notification payload does not contain the value for notification channel id, name, and description.

// Default: "bsft_channel_General"
configuration.setDefaultNotificationChannelId("app_channel_id_default");
// Default: "General"
configuration.setDefaultNotificationChannelName("app_channel_name_default");
// Default: None. This is only set if present in payload or config object.
configuration.setDefaultNotificationChannelDescription("app_channel_description_default");

Deeplinks: Category-based (Deprecated)

We do not recommend the use of category-based deep links as they are soon to be deprecated and not used on the dashboard level. Use the URL-based deep links instead.

// Opens this activity if a push message comes with category "view"
configuration.setProductPage(ProductActivity.class);
// Opens this activity if a push message comes with category "view_cart"
configuration.setCartPage(CartActivity.class);
// Opens this activity if a push message comes with category "promotion"
configuration.setOfferDisplayPage(OfferDisplayActivity.class);

Deeplinks: URL based

When the user clicks on the push notification, the SDK will open the host app's LAUNCHER/MAIN activity and deliver the URL as a string extra inside the bundle with the key "deep_link_url".

To read this value you could make use of the below code snippet.

String deepLinkURL = getIntent().getStringExtra(RichPushConstants.EXTRA_DEEP_LINK_URL);

InApp Messages

In-app messages are not enabled by default. To enable them, call the below two methods.

configuration.setInAppEnabled(true);
// This consent is required to show HTML in-app messages that had JavaScript in them.
configuration.setJavaScriptForInAppWebViewEnabled(true);

Interval

When more than one in-app messages are available for display, the default time interval between two in-app messages is 1 minute. This is the case when the user remains on the same page for 1 minute after dismissing an in-app message. This time interval is configurable with the configuration object as mentioned below.

configuration.setInAppInterval(seconds);

Background fetching

The SDK can fetch the in-app message content from API in the background when a silent push message is received from Blueshift. This is enabled by default in SDK v3.1.1 and higher. If you wish to disable it, you could do it as follows.

configuration.setInAppBackgroundFetchEnabled(false);

Manual Mode

The SDK does the in-app fetching and displaying automatically. If the host app needs full control over this, they can enable manual mode when they initialize the SDK.

When enabled, the SDK

  • will NOT fetch in-app message on app start.
  • will NOT show in-app message automatically (at any cost).
  • will only fetch and store the in-app messages when a silent push is received.
  • will only display in-app message when user invokes the Blueshift.getInstance(this).displayInAppMessages(); method.
configuration.setInAppManualTriggerEnabled(true);

DeviceID source

❗️

If you are an existing Blueshift customer and have not touched this part yet, we want you to exercise caution if you choose a new device ID source. If you have anonymous users (users who use your app without signing in), choosing a new device ID source will delete all the data that we collect.

The SDK is flexible enough to let the host app decide what needs to be collected as "device_id". The default option is Android Advertising ID. The other possible options and their example values are as follows.

ADVERTISING_ID (Default)

The SDK can collect the Android Ad ID as device_id automatically. If no config is provided, this is considered the default configuration.

Min SDK version: 3.0.9 | Example: 65fb85f5-cf16-4616-8b2e-a55c1434fda9

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.ADVERTISING_ID);

INSTANCE_ID

The SDK can collect the Firebase Instance ID and use it as device_id.

Min SDK version: 3.0.9 | Example: d-FEG4gYT6ygf63wEVu4nP

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.INSTANCE_ID);

GUID

The SDK can generate a random GUID and use it as device_id. SDK can cache this value to be used across different app sessions. If required, the host app can reset this value by using a helper method provided in the SDK.

Min SDK version: 3.0.9 | Example: 6ca4a79a-ee53-4372-bb81-165ade978e1f

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.GUID);

ADVERTISING_ID_PKG_NAME

The SDK can collect the Android Ad ID and the package name and form a combination value to be used as device_id.

Min SDK version: 3.1.1 | Example: 65fb85f5-cf16-4616-8b2e-a55c1434fda9:com.blueshift.reads

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.ADVERTISING_ID_PKG_NAME);

INSTANCE_ID_PKG_NAME

The SDK can collect the Firebase Instance ID and the package name and form a combination value to be used as device_id.

Min SDK version: 3.1.1 | Example: d-FEG4gYT6ygf63wEVu4nP:com.blueshift.reads

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.INSTANCE_ID_PKG_NAME);

CUSTOM

Most of the use cases will be covered using the above options. But, sometimes the host app may come with a custom-made device_id. In that case, the SDK can even accept that value and use it in all the events.

Min SDK version: 3.1.4

configuration.setDeviceIdSource(Blueshift.DeviceIdSource.CUSTOM);
String custom_id = getMyCustomDeviceId();
configuration.setCustomDeviceId(custom_id);

Batched events time interval

The SDK lets you send low priority events in batches (of 100 events) to Blueshift's bulk event API at a regular interval of 30min by default. This interval is configurable using the below-mentioned method.

/*
 * This is the time interval used for batching events which are then sent to
 * Blueshift using the bulk events api call. It defaults to 30 min if not set.
 *
 * It is highly recommended to use one of the following for API < 19 devices.
 * AlarmManager.INTERVAL_FIFTEEN_MINUTES
 * AlarmManager.INTERVAL_HALF_HOUR
 * AlarmManager.INTERVAL_HOUR
 * AlarmManager.INTERVAL_HALF_DAY
 * AlarmManager.INTERVAL_DAY
 */
configuration.setBatchInterval(timeInMilliSeconds);

The SDK can send events in both realtime and batches. The last argument of every event tracking method (canBatchThisEvent) defines this behavior. To send events in batches, set it to true.

Ex: Blueshift.getInstance(mContext).trackEvent("event_name", params, true)

We highly recommend the use of real-time events as batched events won't give expected results if you plan to use them in campaigns.

Override Job ID

Our SDK uses JobScheduler for intelligent scheduling of background jobs on Android 21 or higher.

If you use the same in your apps and come across a conflict in Job IDs used, you could override the same as follows.

// for bulk event triggering service's job id
configuration.setBulkEventsJobId(newId);
// for network change listener's job id.
configuration.setNetworkChangeListenerJobId(newId);

Automatic app_open event

The SDK can automatically fire an app_open event of every app start (from the killed state). This can be enabled using the below method.

configuration.setEnableAutoAppOpenFiring(true);

From v3.1.9 onwards, the default behavior is to fire one automatic app_open event in 24 hours. To change this time interval, please make use of the below method.

configuration.setAutoAppOpenInterval(seconds);

Setting Customer Information

Use the UserInfo class to send the customer's details to Blueshift. If the values are set after the customer signs in, they will be used to build the parameters for all the events going forward.

Here is an example of how to set email and customer_id after a customer signs in:

UserInfo userInfo = UserInfo.getInstance(this);

userInfo.setEmail("[email protected]");
userInfo.setRetailerCustomerId("user:12345");

// It is important to save the instance once an updation is made on UserInfo
userInfo.save(context);

Exclude SDK from ProGuard

If you have enabled ProGuard in your project, please exclude the SDK by adding the following lines to your proguard-rules.pro file.

-keep class com.blueshift.** { *; }
-dontwarn com.blueshift.**

Logging

If you are using the SDK version 3.1.1 or higher, no Log messages will be printed. To enable logging, add the following line before initializing the SDK.

BlueshiftLogger.setLogLevel(BlueshiftLogger.VERBOSE);

Disable tracking

Min SDK version 3.1.10

You can now disable sending custom events, push & in-app metrics to the Blueshift. Note that, disabling will drop all the pending events which are yet to send to Blueshift.

The tracking is enabled by default. To disable call,

Blueshift.setTrackingEnabled(context, false);

Messaging opt-out

Push Notifications

You can use Blueshift app preferences to opt-out of push messages that we send from our platform. You can use this functionality if you don't want push messages from our platform to show up on your app.

BlueshiftAppPreferences.getInstance(context).setEnablePush(true);
BlueshiftAppPreferences.getInstance(context).save(context);

InApp Messages

On SDK version 3.2.0 or higher, you can use Blueshift app preferences to opt-out of in-app messages that we send from our platform. You can use this functionality if you don't want in-app messages from our platform to show up on your app.

BlueshiftAppPreferences.getInstance(context).setEnableInApp(true);
BlueshiftAppPreferences.getInstance(context).save(context);

📘

Ensure that you trigger an identify event so that we don't push messages to the customer that you specify.

Point out Blueshift's messages

If you send messages to your customers in addition to the ones from the Blueshift platform, you can use the following helper methods to point out which messages come from our platform:

BlueshiftUtils.isBlueshiftPushMessage(intent);
BlueshiftUtils.isBlueshiftPushMessage(remoteMessage);

Test the SDK integration

These are some of the guidelines to verify the correctness of the SDK integration. The most important thing is to ensure that the app is working as it was before integrating with the SDK.

There are 4 components to verifying the integration:

  • SDK is initialized correctly
    Ensure that certain events are launched correctly from the app, such as identify, click, and app_open.
  • Dashboard
    Confirm that the events show up correctly in the activity of a user on the Blueshift dashboard.
  • Notifications
    Use the push studio editor to create different types of push messages and ensure that the notifications render correctly on devices.
  • Campaigns
    Create a test campaign with the test devices and run a campaign against them to ensure that you are getting stats.

That's it! You are all set to start using the SDK!


What’s Next

Now that you are familiar with our SDK, you can start using it to track events on your app. For more information, see:

Did this page help you?