Notifications: Scripting

This section provides a guide to work with the Notifications module scripting API.

You can access the Notifications module API via the Notifications class under the EasyMobile namespace.

The following snippet shows how you grant, revoke and read the module-level consent of the Notifications module.

// Grants the module-level consent for the Notifications module.
Notifications.GrantDataPrivacyConsent();

// Revokes the module-level consent of the Notifications module.
Notifications.RevokeDataPrivacyConsent();

// Reads the current module-level consent of the Notifications module.
ConsentStatus moduleConsent = Notifications.DataPrivacyConsent;

Initialization

Before notifications can be used, the module needs to be initialized. This initialization should only be done once when the app is loaded, and before any other calls to the API are made. If you have enabled the Auto initialization feature (see Module Configuration section), you don't need to start the initialization from script. Otherwise, if you choose to disable that feature, you can initialize the service using the Init method.

// Initialize push notification service
Notifications.Init();

Note that the initialization should be done early and only once, e.g. you can put it in the Start method of a MonoBehaviour, preferably a singleton so that it won't run again when the scene reloads.

// Initialization in the Start method of a MonoBehaviour script
void Start()
{
    // Initialize push notification service
    Notifications.Init();   

    // Do other stuff...
}

You can check if the module has been initialized at any point using the IsInitialized method.

// Check if initialization has completed.
bool isInitialized = Notifications.IsInitialized();

Working with Local Notifications

Constructing a Notification Content

Before scheduling a notification, you must first prepare its content. To do this simply create a new NotificationContent object and fill it with appropriate information.

// Construct the content of a new notification for scheduling.
NotificationContent PrepareNotificationContent()
{
    NotificationContent content = new NotificationContent();

    // Provide the notification title.
    content.title = "Demo Notification";

    // You can optionally provide the notification subtitle, which is visible on iOS only.
    content.subtitle = "Demo Subtitle";

    // Provide the notification message.
    content.body = "This is a demo notification.";

    // You can optionally attach custom user information to the notification
    // in form of a key-value dictionary.
    content.userInfo = new Dictionary<string, object>();
    content.userInfo.Add("string", "OK");
    content.userInfo.Add("number", 3);
    content.userInfo.Add("bool", true);

    // You can optionally assign this notification to a category using the category ID.
    // If you don't specify any category, the default one will be used.
    // Note that it's recommended to use the category ID constants from the EM_NotificationsConstants class
    // if it has been generated before. In this example, UserCategory_notification_category_test is the
    // generated constant of the category ID "notification.category.test".
    content.categoryId = EM_NotificationsConstants.UserCategory_notification_category_test;

    // If you want to use default small icon and large icon (on Android),
    // don't set the smallIcon and largeIcon fields of the content.
    // If you want to use custom icons instead, simply specify their names here (without file extensions).
    content.smallIcon = "YOUR_CUSTOM_SMALL_ICON";
    content.largeIcon = "YOUR_CUSTOM_LARGE_ICON";

    return content;
}

Scheduling Local Notifications

To schedule a local notification, prepare the notification content and feed it to the ScheduleLocalNotification method.

One-Time Local Notifications

You can schedule a notification to be delivered at a specific time (in the future). If the specified time is in the past, the notification will be delivered immediately.

using System;    // to use DateTime



// Schedule a notification to be delivered by 08:08AM, 08 August 2018.
void ScheduleLocalNotification()
{
    // Prepare the notification content (see the above section).
    NotificationContent content = PrepareNotificationContent();

    // Set the delivery time.
    DateTime triggerDate = new DateTime(2018, 08, 08, 08, 08, 08);

    // Schedule the notification.
    Notifications.ScheduleLocalNotification(triggerDate, content);
}

Instead of a trigger date, you can also schedule a one-time notification to be delivered after some delay time.

using System;



// Schedule a notification to be delivered after 08 hours, 08 minutes and 08 seconds.
void ScheduleLocalNotification()
{
    // Prepare the notification content (see the above section).
    NotificationContent content = PrepareNotificationContent();

    // Set the delay time as a TimeSpan.
    TimeSpan delay = new TimeSpan(08, 08, 08);

    // Schedule the notification.
    Notifications.ScheduleLocalNotification(delay, content);
}

Repeat Local Notifications

If you want the notification to repeat automatically, schedule it to be delivered after some delay time, and then specify a fixed repeat interval. Repeat interval can be one of the following values:

  • None: no repeat
  • EveryMinute: notification repeats once every minute
  • EveryHour: notification repeats once every hour
  • EveryDay: notification repeats once every day
  • EveryWeek: notification repeats once every week
using System;



// Schedule a notification to be delivered after 08 hours, 08 minutes and 08 seconds,
// then repeat once every day.
void ScheduleRepeatLocalNotification()
{
    // Prepare the notification content (see the above section).
    NotificationContent content = PrepareNotificationContent();

    // Set the delay time as a TimeSpan.
    TimeSpan delay = new TimeSpan(08, 08, 08);

    // Schedule the notification.
    Notifications.ScheduleLocalNotification(delay, content, NotificationRepeat.EveryDay);
}

Managing Pending Local Notifications

Get Pending Local Notifications

To get all pending (scheduled but not yet delivered) local notifications, use the GetPendingLocalNotifications method. The pending notifications will be returned as an array of NotificationRequest objects via a callback. Each pending notification request is identified by its request ID.

// Gets all pending local notification requests.
void GetPendingLocalNotifications()
{
    Notifications.GetPendingLocalNotifications(GetPendingLocalNotificationsCallback);
}

// Callback.
void GetPendingLocalNotificationsCallback(NotificationRequest[] pendingRequests)
{
    foreach (var request in pendingRequests)
    {
        NotificationContent content = request.content;        // notification content

        Debug.Log("Notification request ID: " + request.id);    // notification request ID
        Debug.Log("Notification title: " + content.title);
        Debug.Log("Notification body: " + content.body);
    }
}

Cancel a Pending Local Notification

To cancel a particular pending local notification, call the CancelPendingLocalNotification method with the request ID of the notification to be canceled. Canceled notifications will no longer be delivered.

// Cancels a pending local notification with known request ID.
Notifications.CancelPendingLocalNotification("REQUEST_ID_TO_CANCEL");

Cancel All Pending Local Notifications

To cancel all pending local notifications, simply call the CancelAllPendingLocalNotifications method.

// Cancels all pending local notifications.
Notifications.CancelAllPendingLocalNotifications();

Working with Remote Notifications

Remote notifications are sent from a remote server and are typically scheduled from a website, e.g. OneSignal's dashboard. Within your app, you only need to write code to handle when a remote notification is delivered and opened.

Handling Opened Notifications

Whenever a local or remote notification is opened - either by the user tapping on it (default open action) or selecting an action button - your app will be brought to foreground and then a LocalNotificationOpened _or a RemoteNotificationOpened event will be raised. You can subscribe to these events and take appropriate actions according to your app design. It's recommended to subscribe to the events as soon as your app is loaded, e.g. in the _OnEnable method of a MonoBehaviour script in your first scene. Otherwise you risk missing them.

If your app is in foreground when a notification is delivered - be it local or remote - then the notification is not posted (not displayed) and the LocalNotificationOpened or RemoteNotificationOpened event will be raised immediately as if the notification was opened with the default action.

// Subscribes to notification events.
void OnEnable()
{
    Notifications.LocalNotificationOpened += OnLocalNotificationOpened;
    Notifications.RemoteNotificationOpened += OnRemoteNotificationOpened;
}

// Unsubscribes notification events.
void OnDisable()
{
    Notifications.LocalNotificationOpened -= OnLocalNotificationOpened;
    Notifications.RemoteNotificationOpened -= OnRemoteNotificationOpened;
}

// This handler will be called when a local notification is opened.
void OnLocalNotificationOpened(LocalNotification delivered)
{
    // The actionId will be empty if the notification was opened with the default action.
    // Otherwise it contains the ID of the selected action button.
    if (!string.IsNullOrEmpty(delivered.actionId))
    {
        Debug.Log("Action ID: " + delivered.actionId);
    }

    // Whether the notification is delivered when the app is in foreground.
    Debug.Log("Is app in foreground: " + delivered.isAppInForeground.ToString());

    // Gets the notification content.
    NotificationContent content = delivered.content;

    // Take further actions if needed...
}

// This handler will be called when a remote notification is opened.
void OnRemoteNotificationOpened(RemoteNotification delivered)
{
    // The actionId will be empty if the notification was opened with the default action.
    // Otherwise it contains the ID of the selected action button.
    if (!string.IsNullOrEmpty(delivered.actionId))
    {
        Debug.Log("Action ID: " + delivered.actionId);
    }

    // Whether the notification is delivered when the app is in foreground.
    Debug.Log("Is app in foreground: " + delivered.isAppInForeground.ToString());

    // Gets the notification content.
    NotificationContent content = delivered.content;

    // If OneSignal service is in use you can access the original OneSignal payload like below.
    // If OneSignal is not in use this will be null.
    OneSignalNotificationPayload osPayload = delivered.oneSignalPayload;

    // If Firebase Messaging service is in use you can access the original Firebase
    // payload like below. If Firebase is not in use this will be null.
    FirebaseMessage fcmPayload = delivered.firebasePayload;

    // Take further actions if needed...
}

Handling Firebase Notifications on Android

On Android, if a Firebase notification arrives when your app is not running or is in background, only the "data payload" will be sent to the app, while the "notification component" won't because it is intended to be displayed to the user only. Effectively, the NotificationContent associated with the RemoteNotification object returned by the RemoteNotificationOpened event will contain empty fields (title, subtile, body, etc.) with the exception of the 'userInfo' field which represents the data payload. If the app is in foreground then both the data payload and the notification component will be forwarded to the app.

You can learn more about this here and here.

Removing Delivered Notifications

Normally delivered notifications are cleared automatically when they're opened. You can manually clear all previously shown notifications of your app from the notification center or status bar with the ClearAllDeliveredNotifications method.

// Clear all delivered notifications (local and remote).
Notifications.ClearAllDeliveredNotifications();

[iOS] Setting Application Icon Badge Number

iOS allows us to get and set the application icon badge number directly. Easy Mobile provides the following methods so you can manage the badge number when working with notifications on iOS. Note that they don't have any effect on Android.

// Get iOS application icon badge number.
int badgeNumber = Notifications.GetAppIconBadgeNumber();

// Set iOS application icon badge number.
Notifications.SetAppIconBadgeNumber(badgeNumber + 1);    // increase the badge number by 1

results matching ""

    No results matching ""