Android Mobile Notifications With Unity

In this tutorial, you’ll learn about Unity’s Mobile Notifications and how to create and schedule your very own notifications for a Unity app running on an Android device. By JJ Richards.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 3 of this article. Click here to view the first page.

Initializing the System

Your next step will be to set up your system to send notifications by adding some important functions and declarations.”

To start, open the Notification Manager script in your favorite code editor and add these declarations to the script, above the class declaration:

//1
using System;	//for DateTime
//2
using NotificationSamples;
  1. Working with time is a critical piece of managing notifications, and the DateTimefunctions within System provide many useful shortcuts.
  2. NotificationSamples provides access to the MobileNotifications API.

Just under the class declaration, add these variables:

//1
private GameNotificationsManager manager;
//2
public const string ChannelId = "game_channel0";
//3
public const string ReminderChannelId = "reminder_channel1";
//4
public const string NewsChannelId = "news_channel2"; 
  1. Create a private reference to the GameNotificationsManager class that can be used throughout the script.
  2. Declare variable ChannelId and set it to “game_channel0”.
  3. Declare variable ReminderChannelId and set it to “reminder_channel1”.
  4. Declare variable NewsChannelId and set it to “news_channel2”.

Channels are defined as global constants so other scripts can refer to them when setting/sending notifications.

Next, you’ll use the Awake function to provide a reference to the default Game Notifications Manager:

 
void Awake() 
{
    manager = GetComponent<GameNotificationsManager>();
}

You also need to set up channels (mostly for Android) with the following code in Start:

void Start()
{
    //1
    var c1 = new GameNotificationChannel(ChannelId, "Game Alerts", "Game notifications");
    //2
    var c2 = new GameNotificationChannel(NewsChannelId, "News", "News and Events");
    //3
    var c3 = new GameNotificationChannel(ReminderChannelId, 
        "Reminders", "Reminders");
    //4
    manager.Initialize(c1, c2, c3);
}

Each GameNotificationChannel takes three parameters: an id that you created earlier, a short title, and a long title.

  1. Declare a new GameNotificationChannel variable c1 and set it to ChannelId, with a short title of “Game Alerts” and a long title of “Game notifications”.
  2. Declare a new GameNotificationChannel variable c2 and set it to NewsChannelId, with a short title of “News” and a long title of “News and Events”.
  3. Declare a new GameNotificationChannel variable c3 and set it to ReminderChannelId, with a short title of “Reminders” and a long title of “Reminders”.
  4. Now call the Initialize function, passing the channels you just declared.

The system has now been initialized with all the necessary variables to send a notification. Next, it is time to create a function that uses these variables.

Sending a Manual Notification

The core of the system is a generic method to queue a notification with a given set of parameters.

Add this function to the Notification Manager script.

//1
public void SendNotification(string title, string body, DateTime deliveryTime, 
    int? badgeNumber = null, bool reschedule = false, string channelId = null,
    string smallIcon = null, string largeIcon = null) 
{
    //2
    IGameNotification notification = manager.CreateNotification();
    //3
    if (notification == null) 
    {
        return;
    }

    //4
    notification.Title = title;
    //5
    notification.Body = body;
    //6
    notification.Group = 
        !string.IsNullOrEmpty(channelId) ? channelId : ChannelId;
    //7
    notification.DeliveryTime = deliveryTime;
    //8
    notification.SmallIcon = smallIcon;
    //9
    notification.LargeIcon = largeIcon;

    //10   
    if (badgeNumber != null) 
    {
        notification.BadgeNumber = badgeNumber;
    }

    //11
    PendingNotification notificationToDisplay =
        manager.ScheduleNotification(notification);
    //12
    notificationToDisplay.Reschedule = reschedule;
}

While this may seem like a long and complex script, it is actually just a way to process the five required components of a notification. It performs several safety checks and organizes the information to pass to the Mobile Notifications Package before sending it along to the local device UI.

  1. Declare a new method called SendNotification that takes 8 parameters. Each one will be described below.
  2. Declare a new IGameNotification variable notification using the API method manager.CreateNotification().
  3. Add a safety check if the API is unavailable to exit early.
  4. Set the title for the notification by setting the notification.Title variable to the title parameter
  5. Set the body text for the notification by setting the notification.Body variable to the body parameter
  6. If a channelId was passed, use it to set the notification.Group variable, otherwise use the default ChannelId that was set earlier.
  7. Set the time to deliver the notification by setting the notification.DeliveryTime variable to the deliveryTime parameter.
  8. Set the notification.SmallIcon variable to the smallIcon parameter.
  9. Set the notification.LargeIcon variable to the largeIcon parameter.
  10. Optionally, a badge number can be set to display on the application icon if a badgeNumber is passed, by assigning it to the notification.BadgeNumber variable.
  11. Now that all the possible parameters are assigned, declare a new PendingNotification variable notificationToDisplay using the API method manager.ScheduleNotification() and pass notification.
  12. Finally, pass along the optional reschedule bool parameter to notificationToDisplay.Reschedule.

Now that you have a generic way to send a notification, it’s time to create specific implementations connecting to the UI buttons. Insert this code at the bottom of the script.

#region UI buttons

private string smallIconName = "icon_0";
private string largeIconName = "icon_1";

#endregion

This creates a UI Buttons region in the script and sets up the matching references to the assets you selected in the Mobile Notifications Settings.

Implementing the ShortNote

First, you’ll create the ShortNote, which sends a notification quickly after the user presses the button.

To implement this feature, add this code to the UI Buttons region:

//1
private double shortDelay = 10;

public void ShortNote() 
{
    //2
    string title = "Thanks for playing!";
    //3
    string body = "Hope you had fun!";
    //4
    DateTime deliverTime = DateTime.UtcNow.AddSeconds(shortDelay);
    //5
    string channel = ChannelId;
    //6
    SendNotification(title, body, deliverTime, channelId: channel,
        smallIcon: smallIconName, largeIcon: largeIconName );
}
  1. Declare variable shortDelay and set it to 10. This is the number of seconds to wait before sending the notification.
  2. Declare variable title and set it to “Thanks for playing!”.
  3. Declare variable body and set it to “Hope you had fun!”.
  4. Declare variable deliverTime by passing shortDelay to DateTime.UtcNow.AddSeconds.
  5. Declare variable channel and set it to ChannelId.
  6. Then, all the required inputs are sent to the generic SendNotification for processing.

Implementing the LongNote

The LongNote implementation looks very similar, except that it allows for minor changes to timing and messaging.

Add this code to the UI Buttons region as well:

//1
private double longDelay = 60;

public void LongNote() 
{
    //2
    string title = "Play again soon!";
    //3
    string body = "We miss you!";
    //4
    DateTime deliverTime = DateTime.UtcNow.AddSeconds(longDelay);
    //5
    string channel = ChannelId;
    //6
    SendNotification(title, body, deliverTime, channelId: channel,
        smallIcon: smallIconName, largeIcon: largeIconName);
}
  1. Declare variable longDelay and set it to 60. This is the number of seconds to wait before sending the notification.
  2. Declare variable title and set it to “Play again soon!”.
  3. Declare variable body and set it to “We miss you!”.
  4. Declare variable deliverTime by passing longDelay to DateTime.UtcNow.AddSeconds.
  5. Declare variable channel and set it to ChannelId.
  6. Then, all the required inputs are sent to the generic SendNotification for processing.

Save the script and return to the editor. Now that the basic code exists, it’s time to connect it to the buttons in the UI.

JJ Richards

Contributors

JJ Richards

Author

Gijs Bannenberg

Tech Editor

Sandra Grauschopf

Editor

Chris Language

Final Pass Editor

Over 300 content creators. Join our team.