Interface Context

Provides APIs to handle data campaigns, track Item views and interactions, and track manual actions, all within a lifecycle-managed context such as Screen.

1public interface Context

Typically used as Evergage.getScreenForActivity(android.app.Activity), and if necessary, Evergage.getGlobalContext() for behavior outside of an Activity.

Method Summary 

MethodModifier and TypeDescription
addToCart(LineItem lineItem)voidTracks that a line item is being added to the shopping cart.
removeFromCartvoidTracks that a line item is being removed from the shopping cart.
viewCartvoidTracks an entire shopping cart, which will update/replace the entire state of the mirrored cart in Personalization.
comment(Item item)voidTracks that an item was commented on.
favorite(Item item)voidTracks that an item was marked by the user as a favorite item.
isActive()booleanWhether this context is active or not.
purchase(Order order)voidTracks that an order was purchased.
review(Item item)voidTracks that an item was reviewed, with no additional details.
review(Item item, Review reviewDetails)voidTracks that an item was reviewed, with the contents (optional) of the review.
setCampaignHandler(CampaignHandler handler, java.lang.String target)voidTo optionally support custom ‘Data’ campaigns, register a campaign handler for the app-defined target within this context.
share(Item item)voidTracks that an item was shared, for instance by email or on a social network.
trackAction(java.lang.String action)voidSends an event to Personalization describing an action to track.
trackClickthrough(Campaign campaign)voidTracks a clickthrough for the provided data campaign.
trackClickthrough(android.content.Intent notificationIntent)voidTrack an uncommonly handled push notification clickthrough that can’t be automatically tracked.
trackClickthrough(java.util.Map<java.lang.String,java.lang.String> notificationData)voidTrack an uncommonly handled push notification clickthrough that can’t be automatically tracked.
trackDismissal(Campaign campaign)voidTracks a dismissal for the provided data campaign.
trackImpression(Campaign campaign)voidTracks an impression for the provided data campaign.
viewCategory(Category category)voidTracks that a category is being viewed.
viewCategory(Category category, java.lang.String actionName)voidSame as viewCategory(Category) but with a different action name to distinguish this View Category.
viewItem(Item item)voidTracks that an item is being viewed.
viewItem(Item item, java.lang.String actionName)voidSame as viewItem(Item) but with a different action name to distinguish this View Item.
viewItemDetail(Item item)voidTracks that the details of an item are being viewed, such as other product images or a specifications tab.
viewItemDetail(Item item, java.lang.String actionName)voidSame as viewItemDetail(Item) but with a different action name to distinguish this View Item Detail.
viewTag(Tag tag)voidTracks that a tag is being viewed.
viewTag(Tag tag, java.lang.String actionName)voidSame as viewTag(Tag) but with a different action name to distinguish this View Tag.

isActive 

1boolean isActive()

Whether this context is active or not.

A typical Screen context is active when Screen.isRunning() and the app and user are active.

Besides some initial setup just before becoming visible (setCampaignHandler(com.evergage.android.CampaignHandler, java.lang.String), viewItem(com.evergage.android.promote.Item), and so on), activity generally occurs while a context is active. Context activity, in addition to app state and user idleness, can affect campaign delivery. For more information, see setCampaignHandler(com.evergage.android.CampaignHandler, java.lang.String).

Returns

true, if this context is active.

setCampaignHandler 

1void setCampaignHandler(@Nullable CampaignHandler handler, @NonNull String target)

To optionally support custom data campaigns, register a campaign handler for the app-defined target within this context. Can set a null handler for a target to clear.

The “target” is an app-defined string that uniquely identifies the payload data schema - what the data represents and its purpose. See Campaign.getTarget().

While the context, app, and user are active, the handler can receive asynchronous callbacks (on the main thread) with campaigns for the target, in response to actions or events sent. The handler code must show or update the campaign to the user, when appropriate. For example code, see CampaignHandler.

Campaigns can be held for delivery while either:

  • The context, app, or user is inactive
  • No handler is found for the campaign’s target within this context

For each context and target, only the most recent campaign is held.

Lifecycle details:

  • For an Activity, it’s recommended to always get Evergage.getScreenForActivity(Activity) and call this method just before becoming visible, specifically in onStart(). For example code, see CampaignHandler.
  • In order to prevent accidental leaks in the CampaignHandler, a Screen has a limited time to become visible, after which its handlers and held campaigns are cleared.
  • When a screen transitions to not visible onStop(), all handlers and held campaigns are cleared.

Parameters:

ParameterDescription
handlerThe campaign handler this context must use for the specified target.
targetApp-defined string that uniquely identifies the payload data schema - what the data represents and its purpose. For more information, see Campaign.getTarget().

See Also

trackImpression 

1void trackImpression(@NonNull Campaign campaign)

Tracks an impression for the provided data campaign. Call this method after showing the campaign to the user or if the campaign would be shown but the user is in the control group. For more information, see Mobile Data Campaigns and CampaignHandler.

Parameters:

ParameterDescription
campaignThe campaign for which an impression should be tracked.

See Also

trackDismissal 

1void trackDismissal(@NonNull Campaign campaign)

Tracks a dismissal for the provided data campaign. Call this method after showing the campaign to the user and the user dismissed the campaign. For more information, see Mobile Data Campaigns and CampaignHandler.

ParameterDescription
campaignThe campaign for which a dismissal should be tracked.

See Also

trackClickthrough 

1void trackClickthrough(@NonNull Campaign campaign)

Tracks a clickthrough for the provided data campaign. Call this method after showing the campaign to the user and the user clicked campaign content. For more information, see Mobile Data Campaigns and CampaignHandler.

Parameters

ParameterDescription
campaignThe campaign for which a clickthrough should be tracked.

See Also

trackClickthrough(Map) 

1void trackClickthrough(@NonNull Map < String, String > notificationData)

Track an uncommonly handled push notification clickthrough that can’t be automatically tracked.

Personalization automatically tracks clicks/opens from Firebase notifications received in the background, and from Firebase notifications received in the foreground that your app chooses to handle by launching an activity in the default launchMode “standard” (for example, intent did not have flags such as FLAG_ACTIVITY_CLEAR_TOP). Any Activity using a different launchMode can enable tracking by calling setIntent within onNewIntent, as shown in the following example.

1@Override
2protected void onNewIntent(Intent intent) {
3    super.onNewIntent(intent);
4    setIntent(intent);
5}

This tracking method may be required if you manually render a notification from the push. For example, if the Firebase notification is received while the app is in the foreground, it is not automatically shown - instead FirebaseMessagingService#onMessageReceived is called. At this point your app can decide if it wants to manually show a notification. For example code using notifications, see trackClickthrough(Intent).

The following code example uses an AlertActivity/Dialog.

1// In Firebase Messaging Service
2@Override
3public void onMessageReceived(final RemoteMessage remoteMessage) {
4    super.onMessageReceived(remoteMessage);
5
6    Map & lt;
7    String, String & gt;
8    data = remoteMessage.getData();
9    RemoteMessage.Notification notification = remoteMessage.getNotification();
10    if (notification == null) {
11        // ... process data, but typically nothing to show user unless content within data
12        return;
13    }
14
15    // ...app logic decides to show an alert-styled Activity...
16
17    Intent alertIntent = new Intent(this, AlertActivity.class);
18    alertIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
19    alertIntent.putExtra("remoteMessage", remoteMessage);
20    startActivity(alertIntent);
21}
22
23// In your app manifest
24<activity
25    android: name = ".AlertActivity"
26    android: launchMode = "singleInstance"
27    android: taskAffinity = ""
28    android: excludeFromRecents = "true"
29    android: noHistory = "true" / >
30
31// AlertActivity
32public class AlertActivity extends Activity {
33    private AlertDialog currentDialog;
34
35    @Override
36    protected void onCreate(@Nullable Bundle savedInstanceState) {
37        super.onCreate(savedInstanceState);
38        setVisible(false);
39        handleAlertIntent(getIntent());
40    }
41
42    @Override
43    protected void onNewIntent(Intent intent) {
44        super.onNewIntent(intent);
45        // Another potential alert has arrived
46        handleAlertIntent(intent);
47    }
48
49    private void handleAlertIntent(Intent intent) {
50        overridePendingTransition(0, 0);
51        Parcelable parcelable = intent != null ? intent.getParcelableExtra("remoteMessage") : null;
52        final RemoteMessage remoteMessage = (parcelable instanceof RemoteMessage) ? (RemoteMessage) parcelable : null;
53        if (remoteMessage != null && remoteMessage.getNotification() != null) {
54            // New dialog build
55            AlertDialog.Builder builder = new AlertDialog.Builder(this)
56                .setTitle(remoteMessage.getNotification().getTitle())
57                .setMessage(remoteMessage.getNotification().getBody())
58                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
59                    @Override
60                    public void onClick(DialogInterface dialogInterface, int i) {
61
62                        // *** TRACKING THE CLICK: ***
63                        com.evergage.android.Context globalContext = Evergage.getInstance().getGlobalContext();
64                        if (globalContext != null) {
65                            globalContext.trackClickthrough(remoteMessage.getData());
66                        }
67
68                        exitIfNoContent(dialogInterface);
69                    }
70                });
71
72            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
73                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
74                    @Override
75                    public void onDismiss(DialogInterface dialogInterface) {
76                        exitIfNoContent(dialogInterface);
77                    }
78                });
79            } else {
80                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
81                    @Override
82                    public void onCancel(DialogInterface dialogInterface) {
83                        exitIfNoContent(dialogInterface);
84                    }
85                });
86            }
87
88            // Remove previous dialog
89            AlertDialog previousDialog = currentDialog;
90            currentDialog = null;
91            if (previousDialog != null) {
92                previousDialog.hide();
93            }
94
95            // Show new dialog
96            currentDialog = builder.create();
97            currentDialog.show();
98        }
99
100        exitIfNoContent(null);
101    }
102
103    private void exitIfNoContent(@Nullable DialogInterface dialogBeingDismissed) {
104        if (currentDialog != null && currentDialog != dialogBeingDismissed) {
105            return;
106        }
107
108        currentDialog = null;
109        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
110            finishAndRemoveTask();
111        } else {
112            finish();
113        }
114        overridePendingTransition(0, 0);
115    }
116}

Parameters

ParameterDescription
notificationDataPass remoteMessage.getData(), after it’s been manually rendered and clicked.

Since

1.3.0

See Also

trackClickthrough(Intent) 

1void trackClickthrough(@NonNull android.content.Intent notificationIntent)

Track an uncommonly handled push notification clickthrough that can’t be automatically tracked.

Personalization automatically tracks clicks/opens from Firebase notifications received in the background, and from Firebase notifications received in the foreground that your app chooses to handle by launching an activity in the default launchMode “standard” (for example, intent did not have flags such as FLAG_ACTIVITY_CLEAR_TOP). Any Activity using a different launchMode can enable tracking by calling setIntent within onNewIntent:.

1@Override
2protected void onNewIntent(Intent intent) {
3    super.onNewIntent(intent);
4    setIntent(intent);
5}

This tracking method may be required if you manually render a Notification from the push. For example, if the Firebase notification is received while the app is in the foreground, it is not automatically shown - instead FirebaseMessagingService#onMessageReceived is called. At this point your app can decide if it wants to manually show a notification. See trackClickthrough(Map) for an example using an AlertActivity/Dialog.

The following is example code that uses intents for an Activity and BroadcastReceiver.

1// In the FirebaseMessagingService:
2@Override
3public void onMessageReceived(final RemoteMessage remoteMessage) {
4    super.onMessageReceived(remoteMessage);
5
6    Map&lt;String, String&gt; data = remoteMessage.getData();
7    RemoteMessage.Notification notification = remoteMessage.getNotification();
8    if (notification == null) {
9        // ... process data, but typically nothing to show user unless content within data
10        return;
11    }
12
13    // ...app logic decides to show an alert-styled Activity...
14
15    // Need to get RemoteMessage data into intent extras for tracking
16    Bundle bundle = new Bundle();
17    Map&lt;String, String&gt; data = remoteMessage.getData();
18    if (data != null) {
19        for (Map.Entry&lt;String, String&gt; entry : data.entrySet()) {
20            bundle.putString(entry.getKey(), entry.getValue());
21        }
22    }
23    // Your app might instead have a specific id in remoteMessage.getData()
24    int notificationId = RANDOM.nextInt(Integer.SIZE-1);
25    bundle.putInt("notificationId", notificationId);
26
27    // See https://developer.android.com/training/notify-user/build-notification
28
29    // This Activity intent should automatically track, though you may need onNewIntent (see method doc above)
30    Intent activityIntent = new Intent(this, MainActivity.class);
31    activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
32    activityIntent.putExtras(bundle);
33    PendingIntent pendingActivityIntent = PendingIntent.getActivity(this, 0, activityIntent, PendingIntent.FLAG_ONE_SHOT);
34
35    // This non-Activity intent's click handler will need to use this method to track, see AlertBroadcastReceiver below
36    Intent broadcastIntent = new Intent(this, AlertBroadcastReceiver.class);
37    broadcastIntent.setAction("Action");
38    broadcastIntent.putExtras(bundle);
39    PendingIntent pendingBroadcastIntent = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_ONE_SHOT);
40
41    NotificationCompat.Builder notificationBuilder =
42        new NotificationCompat.Builder(this, "default")
43            .setContentTitle(remoteMessage.getNotification().getTitle())
44            .setContentText(remoteMessage.getNotification().getBody())
45            .setSmallIcon(R.mipmap.ic_launcher)
46            .setAutoCancel(true)
47            .setContentIntent(pendingActivityIntent)
48            .addAction(R.mipmap.ic_launcher, "Action", pendingBroadcastIntent);
49
50    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
51    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
52        NotificationChannel channel = new NotificationChannel(
53            "default", "Notifications", NotificationManager.IMPORTANCE_DEFAULT);
54        notificationManager.createNotificationChannel(channel);
55    }
56    notificationManager.notify(notificationId, notificationBuilder.build());
57}
58
59
60// In your app manifest:
61<receiver
62    android:name=".AlertBroadcastReceiver"
63    android:exported="false" />
64
65
66// AlertBroadcastReceiver:
67public class AlertBroadcastReceiver extends BroadcastReceiver {
68    @Override
69    public void onReceive(Context context, Intent intent) {
70        int notificationId = intent.getIntExtra("notificationId", -1);
71        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
72        if (notificationId >= 0 && notificationManager != null) {
73            // Clear notification:
74            notificationManager.cancel(notificationId);
75
76            // *** TRACKING THE CLICK: ***
77            com.evergage.android.Context globalContext = Evergage.getInstance().getGlobalContext();
78            if (globalContext != null) {
79                globalContext.trackClickthrough(intent);
80            }
81
82            // ...any app-specific processing
83        }
84    }
85}

Parameters

ParameterDescription
notificationIntentThe intent containing extras from the original remoteMessage.getData(), after the notification has been manually rendered and clicked

Since

1.3.0

See Also

viewItem 

1void viewItem(@Nullable Item item)

Tracks that an item is being viewed.

Set null to indicate no longer viewing any item/category/tag.

For an Activity Screen, it is recommended to call this method within onStart() or onResume() before super.onResume(), if the item is known at that time.

Personalization will automatically track the time spent viewing the item while the context, app, and user is active. The item will remain the one viewed until viewItem or viewItemDetail(com.evergage.android.promote.Item) are called again.

Parameters

ParameterDescription
itemThe item being viewed.

See Also

viewItem(Item, String) 

1void viewItem(@Nullable Item item,
2    @Nullable String actionName)

Same as viewItem(Item) but with a different action name to distinguish this View Item. Only tracks an action if item is non-null.

Parameters

ParameterDescription
itemThe item being viewed.
actionNameOptional different action name.

Since

1.3.0

viewItemDetail 

1void viewItemDetail(@Nullable Item item)

Tracks that the details of an item are being viewed, such as other product images or a specifications tab. Set null to indicate no longer viewing any item/category/tag.

For an Activity Screen, it is recommended to call this method within onStart() or onResume() before super.onResume(), if the item is known at that time.

Personalization will automatically track the time spent viewing the item while the context, app, and user is active. The item will remain the one viewed until this method or viewItem(com.evergage.android.promote.Item) are called again.

Parameters

ParameterDescription
itemThe item whose details are being viewed.

See Also

viewItemDetail(Item, String) 

1void viewItemDetail(@Nullable Item item,
2    @Nullable String actionName)

Same as viewItemDetail(Item) but with a different action name to distinguish this View Item Detail.

Only tracks an action if the item is non-null.

Parameters

ParameterDescription
itemThe item whose details are being viewed.
actionNameOptional different action name.

Since

1.3.0

viewCategory 

1void viewCategory(@Nullable Category category)

Tracks that a category is being viewed.

Set null to indicate no longer viewing any item/category/tag.

For an Activity Screen, it is recommended to call this method within onStart() or onResume() before super.onResume(), if the category is known at that time.

Parameters

ParameterDescription
categoryThe category being viewed.

See Also

viewCategory(Category, String) 

1void viewCategory(@Nullable Category category,
2    @Nullable String actionName)

Same as viewCategory(Category) but with a different action name to distinguish this View Category.

Only tracks an action if the category is non-null.

Parameters

ParameterDescription
categoryThe category being viewed.
actionNameOptional different action name.

Since

1.3.0

viewTag 

1void viewTag(@Nullable Tag tag)

Tracks that a tag is being viewed. Set null to indicate no longer viewing any item/category/tag.

For an Activity Screen, it is recommended to call this method within onStart() or onResume() before super.onResume(), if the tag is known at that time.

Parameters

ParameterDescription
tagThe tag being viewed.

See Also

viewTag(Tag, String) 

1void viewTag(@Nullable Tag tag,
2    @Nullable String actionName)

Same as viewTag(Tag) but with a different action name to distinguish this View Tag. Only tracks an action if the tag is non-null.

Parameters

ParameterDescription
tagThe tag being viewed.
actionNameOptional different action name.

Since

1.3.0

addToCart 

1void addToCart(@NonNull LineItem lineItem)

Tracks that a line item is being added to the shopping cart.

Parameters

ParameterDescription
lineItemThe line item being added. The LineItem.item should be a Product with a set Product.price.

removeFromCart 

1void removeFromCart(@NonNull LineItem lineItem);

Tracks that a line item is being removed from the shopping cart.

Parameters

ParameterDescription
lineItemThe line item being removed. The LineItem.item should be a Product with a set Product.price.

Since

1.4.0

viewCart 

1void viewCart(@NonNull Order order)

Tracks an entire shopping cart, which will update/replace the entire state of the mirrored cart in Personalization. A cart can be considered an “open” order. Most carts will not have an orderId, and so the field can be left un-set.

Parameters

ParameterDescription
orderThe entire cart being viewed. Each LineItem.item should be a Product with a set Product.price.

Since

1.4.0

purchase 

1void purchase(@NonNull Order order)

Tracks that an order was purchased. If the order contains no lineItems, the lineItems currently in the cart will be used. If orderId is set and multiple purchase events are received for the same orderId, only the first will be used (all others will be ignored.)

Parameters

ParameterDescription
orderThe order that was purchased. Each LineItem.item should be a Product with a set Product.price.

review 

1void review(@NonNull Item item)

Tracks that an item was reviewed, with no additional details. Equivalent of calling review(Item, Review) with null for the optional review details.

Parameters

ParameterDescription
itemThe item that was reviewed.

review(Item, Review) 

1void review(@NonNull Item item,
2            @Nullable Review reviewDetails)

Tracks that an item was reviewed, with the contents (optional) of the review.

Parameters

ParameterDescription
itemThe item that was reviewed.
reviewDetailsThe optional contents of the review, such as the rating.

share 

1void share(@NonNull Item item)

Tracks that an item was shared, for instance by email or on a social network.

Parameters

ParameterDescription
itemThe item that was shared.

comment 

1void comment(@NonNull Item item)

Tracks that an item was commented on. For instance, an article or blog might accept comments.

Parameters

ParameterDescription
itemThe item that was commented on.

favorite 

1void favorite(@NonNull Item item)

Tracks that an item was marked by the user as a favorite item. This is an explicit action taken by the user (often indicated by a single star).

Parameters

ParameterDescription
itemThe item that was marked as favorite.

trackAction 

1void trackAction(@NonNull String action)

Sends an event to Personalization describing an action to track. When considering the action name, remember that datasets encompass multiple platforms and apps. The name can match a corresponding action/behavior from another platform/app. A campaign can use a source rule to be limited to a specific source or set of sources. For information on recommended rules, see Mobile Data Campaigns.

Actions sent from this context (including Item APIs) can potentially receive a campaign in response, delivered to a handler via setCampaignHandler(com.evergage.android.CampaignHandler, java.lang.String).

Parameters

ParameterDescription
actionA short string that identifies the action.