What you will learn:

By integrating our SDK, you can display Notifications on your app when a beacon is detected nearby.

To make things easier, our SDK contains a default Auto Notification: this is a built-in notification that is automatically generated when a beacon is detected nearby, as soon as the SDK has been initialized in your app.

You also have the ability to configure custom-built notifications, using our model of interfaces and built-in objects.

In both cases, you can manage the content of your beacon notifications directly on our AdTag platform.

This tutorial tells you more about these Auto and custom-built beacon notifications, and how you can work with them.

Prerequisites - What you need to get started

  • Your SDK credentials, including an SDK Login, Password, and Company Key to initialize the SDK.
  • A BLE beacon, which has been configured on your account, in order to test interactions with your app.
  • An Android Device, with Bluetooth 4.0 and Android 4.0 and above, to be able to interact with BLE beacons.
  • The Android Studio application, which you can download from the Android Developers website.
  • You must have completed the 5 minutes QuickStart Tutorial.

Initialize the SDK

Step 1: Clone the sdk-tutorial repository

  • Clone the sdk-tutorial repository
git clone https://github.com/Connecthings/sdk-tutorial.git
  • Open the android>beacon>notification>Starter project with Android Studio

Step 2: Configure the SDK

  • Open the ApplicationNotification class
  • Configure the SDK with:
    • the appropriate Adtag Environment (DEMO / PREPROD / PROD / PROD_US)
    • your SDK credentials (your login, password, and company details from Connecthings )
	AdtagInitializer.initInstance(this)
					.initUrlType(UrlType.DEMO / ... / UrlType.PROD)
					.initUser("YOUR_USER",  "YOUR_PWD")
					.initCompany("YOUR_COMPANY_KEY").synchronize();

If you need more informations, have a look to the 5 minutes quickstart tutorial

Work with Auto Notifications

As a reminder, Auto Notifications are notifications generated by default by the SDK. You can manage their content (text – title & description, URI, and image), and disable them if necessary, directly from the AdTag platform, in the Application Management section. The icon associated with the notification can also be customized through the SDK.

Learn more on notification management in AdTag in the AdTag tutorial

Personalizing the notification icon

You can customize the icon associated with your Auto Notification (not to be confused with the content image associated with the notification, which is managed in AdTag), by adding the following to your drawable resources folder:

  • icon_notification_android_4 - for Android 4 or below.
  • icon_notification for Android 5 or above.

Personalizing the notification channel

Starting from Android O, the notifications are displayed in a specific channel. This channel is shared with the Welcome Notifications.

You can customize the beacon notification channel, creating a dedicated resource file with the following keys:

<resources>
    <string name="cp_channel_name">Proximity Notifications</string>
    <string name="cp_channel_description">Description</string>
    <integer name="cp_channel_importance">2</integer>
    <bool name="cp_channel_enable_light_color">false</bool>
    <color name="cp_channel_light_color">#0e71ce</color>
    <bool name="cp_channel_enable_vibration">false</bool>
    <integer-array name="cp_channel_vibration_pattern">
        <item>1000</item>
        <item>1000</item>
        <item>1000</item>
    </integer-array>
    <string name="cp_channel_sound_uri"></string>
    <integer name="cp_channel_sound_content_type">2</integer>
    <integer name="cp_channel_sound_usage">5</integer>
    <integer name="cp_channel_lock_screen_visibility">1</integer>
    <integer name="cp_notif_turn_on_lock_screen_time_out">0</integer>
</resources>

These are the default values used to setup the notification channel.

Note 1:

Prior to Android O, the SDK uses theses values to also setup the deprecated notification builder parameters (such as the priority, the vibration, and the sound) when generating a notification.

Note 2:

The cp_notif_turn_on_lock_screen_time_out is not a parameter of the channel. It's a specific option of the SDK which allows to turn on the lock screen for few seconds when receiving a notification.

For example, if you set 1000 for the cp_notif_turn_on_lock_screen_time_out parameter, the lock screen will turn on for 1 second when receiving a notification.

Create custom-built notifications

If you would like to implement notifications that are more customizable than our Auto notifications, you can replace them with your own, custom-built beacon notifications, as described in the following section.

Notification Model Overview

First, let’s go through an overview of the notification model, with the corresponding interfaces and built-in objects.

The NotificationTask

The NotificationTask is a generic interface that allows your application to complete an asynchronous task of your choice before displaying a notification.

The method launchNotificationTask takes two parameters:

  • PlaceNotification: the common object used by the SDK to deal with notification
  • DisplayPlaceNotificationListener: the object used to notify the SDK when the notification is ready to be displayed

The DisplayPlaceNotificationListener

The DisplayPlaceNotificationListener is an interface that is mainly in charge of displaying the notification linked with a beacon. Before a notification is triggered, the NotificationManager checks that the corresponding beacon is still within range. If so, the notification is displayed; otherwise, nothing appears to the end user. To notify the NotificationManager of the need to display a notification, you must call the displayPlaceNotification method, which takes a PlaceNotificationImage object as argument.

The NotificationImageTask

The NotificationImageTask is a specific implementation of the NotificationTask interface. It directly downloads the notification image from AdTag and, when ready, displays the beacon notification with the corresponding image for Android 4 and above.

The NotificationBuilder

The NotificationBuilder interface allows you to create native Notifications once all your asynctasks are finished.

If you want to create and use your own builder, you need to implement two methods:

  • generateNotificationBuilder: generates and returns the end native notification (through a NotificationCompat.Builder), the method takes one argument - a PlaceNotificationImage.
  • generateIntentPackage: gives you the possibility to associate an intent package to your notification, the method takes one argument - a PlaceNotificationImage.

PlaceNotificationImage

A PlaceNotificationImage has additional methods compared to the PlaceNotification object, for example the following methods:

  • getImage: returns the bitmap associated with the notification image on AdTag
  • hasImage: returns true if the image bitmap is available
  • getThumbnail: returns the bitmap associated with the thumbnail on AdTag
  • hasThumbnail: returns true if the thumbnail bitmap is available
  • isWelcomeNotification: returns true if the associated placeNotification is a welcome notification

What can you customize ?

  • The NotificationTask, allows you to associate additional content to the notification in an async way (as bitmap). This option will not be discussed in this document, but you can find a basic implementation to help you to start in the notification demo code folder.
  • The NotificationBuilder, allows you to have a full control on the notification parameters and content in the operating system. The next step will develop an implementation of the NotificationBuilder interface.

Step 1: Create your own NotificationBuilder

  • Create a new class named MyNotificationBuilder
  • Implement the NotificationBuilder interface on this class
public class MyNotificationBuilder implements NotificationBuilder {
    @Override
    public NotificationCompat.Builder generateNotificationBuilder(PlaceNotificationImage placeNotificationImage) {

    }

    @Override
    public Intent generateIntentPackage(PlaceNotificationImage placeNotificationImage) {

    }
}
  • Add a Context variable and the associated constructor.
private Context context;

public MyNotificationBuilder(Context context) {
    this.context = context.getApplicationContext();
}

Step 2: Set up the notification intent

  • Define the Activity that will be launched when a user clicks on a notification
  • We strongly recommend that you leverage the URI field available in AdTag to configure a deep link. This way you can edit it at any point directly from the platform without having to modify your app:
@Override
public Intent generateIntentPackage(PlaceNotificationImage placeNotificationImage) {
    PackageManager packageManager = this.context.getPackageManager();
    Intent intentPackage;
    if (TextUtils.isEmpty(placeNotificationImage.getDeepLink())) {
        intentPackage = packageManager.getLaunchIntentForPackage(this.context.getPackageName());
        intentPackage.addCategory(Intent.CATEGORY_HOME);
    } else {
        intentPackage = new Intent(Intent.ACTION_VIEW, Uri.parse(placeNotificationImage.getDeepLink()));
    }
    intentPackage.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return intentPackage;
}

Note:

In your Activity, you can retrieve the PlaceNotification object, using the following method:

getIntent().getExtras().getParcelable(NotificationManager.NOTIFICATION_CONTENT);

Step 3: Generate the native notification

  • Create a native notification based on the content of the PlaceNotificationImage object
@Override
public NotificationCompat.Builder generateNotificationBuilder(PlaceNotificationImage placeNotificationImage) {
    PlaceNotification placeNotification = placeNotificationImage.getPlaceNotification();

    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(context);
    mNotificationBuilder.setContentTitle(placeNotification.getTitle());
    mNotificationBuilder.setContentText(placeNotification.getDescription());

    if (placeNotification.hasImage()) {
        NotificationCompat.BigPictureStyle style = new NotificationCompat
                .BigPictureStyle()
                .bigPicture(placeNotificationImage.getImageBitmap());
        if (placeNotification.hasThumbnail()) {
            style.bigLargeIcon(placeNotificationImage.getThumbnailBitmap());
        }
        mNotificationBuilder.setStyle(style);
    }

    mNotificationBuilder.setSmallIcon(R.drawable.icon_notification_ble_ask_permission);
    mNotificationBuilder.setAutoCancel(true);
    return mNotificationBuilder;
}

Note:

The PlaceNotificationImage object contains the content associated with the beacon in AdTag, moreover it can also contain the image downloaded thanks to the NotificationTask. To access the content, you can use the method getPlaceNotification() which returns an interface with the following main methods :

  • getTitle(): retrieves the title of the notification
  • getDescription(): retrieves the description of the notification

The SDK has an implementation of the PlaceNotification called AdtagPlaceNotification. In this object, you can also find an AdtagContent object. Through it, you can base the text of your notifications on other AdTag categories & fields of your choice, using the method adtagContent.getValue(CATEGORY, FIELD).

For example, adtagContent.getValue("LINE", "DIRECTION") allows to retrieve the DIRECTION field of the LINE category for a real-time transit schedule use case.

Step 4: Register your MyNotificationBuilder

  • Open the ApplicationNotification class
  • First initialize the SDK
  • Get an instance of the AdtagBeaconManager class and register an instance of our MyNotificationBuilder class thanks to the method registerNotificationBuilder()
public void onCreate(){
    AdtagInitializer.getInstance()
            .initContext(this)
            .initUrlType(Url.UrlType.PROD)
            .initUser("user", "pass")
            .initCompany("company")
            .synchronize();

    AdtagInitializer.getInstance().addPermissionToAsk(Manifest.permission.ACCESS_COARSE_LOCATION);

    AdtagBeaconManager beaconManager = AdtagBeaconManager.getInstance();
    beaconManager.registerNotificationBuilder(new MyNotificationBuilder(this));
}

Note:

The AdtagBeaconManager only accepts one NotificationBuilder.

In other words, if you register a new NotificationBuilder, the existing one will be automatically replaced.

Start testing

If your beacon is already emitting, you must stop/restart the emission process in order to simulate a new entry region for your smartphone, and generate a notification.

There are 2 solutions to stop/restart the emission process:

  • You can put the beacon inside a microwave (but don't start it!)
  • You can remove the battery from the beacon (in that case, depending on the model, it can take up to 30 seconds for the beacon to start emitting again after you reinsert the battery)
  1. In Android Studio, launch the installation of the application you have just built on your mobile phone.

  2. On Android 6 and above, when the application starts, a popup asks for permission to access your smartphone’s location: grant it!

  3. Close your application or leave it running in the background

  4. Remove the beacon from the microwave or reinsert the battery.

  5. Wait for a few seconds (maximum 1 minute)

  6. Click on the notification that has appeared on your screen just for fun.

Note 1:

Some Android 6 and above smartphone models now need location to be activated in order to enable background beacon detection.

Note 2:

On Android, the image associated with a notification can only be displayed if the notification is the first in the smartphone’s list. Some OS versions & smartphone brands offer their users the ability to extend the notification to view the image, when it is not the first in the list.