Home · Unity Tutorials

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.

4/5 2 Ratings

Version

  • C# 7.3, Unity 2019.3, Unity

Ding! Time to wake up.
Ding! You have an appointment in 30 minutes.
Ding! Tomorrow is your mother’s birthday.

Notifications are a common and valuable part of modern life, so it’s natural to expect your favorite mobile apps and games to use them too. 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. Notifications will take your apps to the next level, helping you to retain user attention and also to keep your users informed.

Notifications on an Android device

Note: This tutorial assumes you know the basics of Android development in Unity. If you are new to the subject, check out our Unity for Beginners series first. For this tutorial, you’ll need Unity 2019.3.0f3 or later. Make sure you’ve installed Android build support as well.

Getting Started

Download the project by clicking the Download Materials button at the top or bottom of the tutorial.

Open the starter project and look at the folder structure in the Project window.

Folder setup in the Project window

In Assets ► RW, you’ll find everything you need for the project:

  1. Scenes: Contains the NotificationTutorial scene.
  2. Scripts: Empty folder for the script you’ll create.
  3. Textures: Contains sample art for you to use.
  4. Prefabs: A sample interface for you to use.

Take a quick look at the NotificationTutorial scene in the Scenes folder. You’ll notice that it’s just an empty scene with nothing much going on. It represents a typical Unity app with no Notification capabilities. In the steps to follow, you’ll be adding some basic UI elements, you’ll also be adding the required components and scripts to enable this Unity app to send Notifications.

Now you’re ready to start getting noticed! :]

Setting the Scene

Since this is an Android tutorial, make sure you select Android as the platform in your Build Settings. Open the Package Manager and you’ll see that TextMeshPro and Mobile Notifications are already imported.

The Package Manager's setup

Open the NotificationTutorial scene inside the Scenes folder. You’ll find a very basic scene with a camera, a Screen Overlay Canvas and an EventSystem. Set your Game view to Portrait to match the default orientation configured in Project Settings ► Player.

Start by creating a title for the main page. Select Canvas in the Hierarchy, add a UI ► Text – TextMeshPro GameObject and call it Title. Give the text field a catchy name: Notation Tutorial.

Create an empty GameObject under Canvas to hold some buttons. Call it ButtonGroup and add a Horizontal Layout Group component to adjust the layout as you like. You can also adjust the RectTransform to suit your preferences.

Next, create two buttons by selecting ButtonGroup in the Hierarchy and then right-clicking to select UI ► Button-TextMeshPro.

You’ll use the first button to send a single notification after a short delay, so name it ShortNote. Set the Text to Notify in 10 seconds.

You’ll use the second button to schedule a single notification after a long delay, so name it LongNote. Set the Text to Notify in one minute.

If you don’t want to set this up yourself, there’s a prefab ready to import in RW ► Prefabs.

Notifications Tutorial with two buttons set up

The UI is now complete. Before implementing specific notifications, take a moment to consider why notifications are important for your app.

Using Notifications to Improve Retention

One of the primary benefits of notifications is the positive impact they have on player retention. Notifications help bring players back to a game they haven’t played in a while. These player lapses are often addressed on a 3-day, 7-day or 30-day cycle from the player’s last active session.

Notifications help players start a session at the right time via timers and alerts related to gameplay events. For example, you might notify players when the smithy has finished their brand new sword or their castle is under attack.

You can also use notifications to improve retention by alerting players about scheduled events and tournaments, whether created by the developer or other players.

All these examples are compelling reasons for a player to come back to a game, and notifications are a great way to remind players about those reasons.

Understanding Notifications

The notification itself has five parts that you’ll need to create and provide:

  1. Title: A short, bolded text.
  2. Description: A longer, non-bolded text.
  3. Small icon: A small, pure white icon that appears throughout the device UI.
  4. Large icon: A large, colored icon that only appears when space in the UI is available.
  5. Delivery date: The date and time when the app should notify the user.

As the app developer, you don’t control the device UI or how the user interacts with the notification – that’s the job of the device OS. Your job is to supply all five parts of the notification so the device OS can properly send the message according to a variety of user scenarios.

Now that you have an idea of the structure behind the notifications, it’s time to get your assets ready to go.

Prepping Assets

To have the best effect, your notifications shouldn’t only be timely, they should also be attractive. For that, you’ll need some artwork.

Unity’s Mobile Notifications Package provides an easy way to manage the art assets you need to create for notifications. This tutorial uses Mobile Notifications Package preview.5 – 1.0.4 from Unity’s Package Manager. You can find the Mobile Notifications Settings under Project Settings.

Your first step is to set up three icons:

  1. For Identifier icon-0 with Type Small Icon, select the icon_timer asset.
  2. Next, for Identifier icon_1, which has Type Large Icon, select the RW_Icon_macOS_256 asset.
  3. Finally, for Identifier alarm, with Type Small Icon, select the icon_notification_bell asset.

These identifiers need to match the script that you’ll create next. The settings dialog should look like this:

Mobile Notifications Settings screen

The scene also needs a way to process notifications.

To set these up, create an empty GameObject called NotificationManager. The scene hierarchy should now look like this:

Current screen hierarchy

Select that GameObject and add a Game Notifications Manager component, which comes with the Mobile Notifications Package.

Inside Scripts, create a new C# script named NotificationManager. Attach that script to the NotificationManager GameObject as well.

Notifications Manager setup

Now that all the pieces are in place, it is time to connect them.

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.

Setting up the UI Buttons

In the Hierarchy, select the Button component of the ShortNote GameObject, create a new OnClick event by clicking the + button at the bottom-right and drag the NotificationManager GameObject into the newly-created OnClick slot. In the drop-down, select NotificationManager.ShortNote.

Setting up the ShortNote

Repeat that step for the LongNote GameObject, assigning NotificationManager.LongNote.

Save the scene and the project. You’re ready to deploy a build to your Android device.

Test by clicking your new buttons and waiting for the notifications to appear. Try it with the app open and closed. The notifications should still appear as scheduled.

Notifications successfully arriving on a device

Congratulations, you have mastered the basics of notifications. Next, it’s time for something a little more advanced.

Scheduling a Group of Notifications

Retention reminders and scheduled events are powerful forms of notifications, which differ slightly from the basic time-delay format.

Retention Reminders

You should be able to cancel retention reminders if the player returns before they occur. For example, reminding the player to return 3-days, 7-days, and 30-days after their last session is a common approach.

If the player never returns, they’ll get three notifications on the 3rd, 7th and 30th day. But imagine they come back on the 5th day. The previously-scheduled reminders for the 7th and 30th day need to be canceled. And all three reminder days need to be reset from the new current play date.

To create retention reminders, add the following code to the Notification Manager:

private string retentionIconName = "icon_0";
private string retentionLargeIconName = "icon_1";

//Schedule notification relative to current game session
//Change this from seconds to days after testing
private void RetentionReminderTest(int seconds) 
{
    string title = "We miss you!";
    string body = string.Concat("You've been away for ",seconds," seconds");
    DateTime deliverTime = DateTime.UtcNow.AddSeconds(seconds);
    string channel = ReminderChannelId;

    SendNotification(title, body, deliverTime, channelId: channel,
        smallIcon: retentionIconName, largeIcon: retentionLargeIconName);
}

If you think this looks a lot like both ShortNote and LongNote, you’re right! It’s simply a generic form that takes the amount of time to wait as a parameter. So you can call it with any amount of time that you need.

Scheduled Events

Scheduled events need to happen at a specific date and time, regardless of when the player last used the app. Maybe there’s a recurring event on the 15th of every month or a one-time event scheduled for a specific holiday, like Mother’s Day. DateTime.UtcNow.AddSeconds doesn’t help in this scenario, so you’ll need to create another specific function to schedule these notifications by adding the following code to the Notification Manager:

private string eventIconName = "alarm";
private string eventLargeIconName = "icon_1";

//Schedule notification to a specific DateTime
//Change this from minutes to a specific DateTime or daysOfTheMonth
private void EventAlarmTest(int minutesOnTheHour) 
{
    string title = "Event is Starting!";
    string body = string.Concat("It's ", minutesOnTheHour, " minutes after the hour");
    DateTime deliverTime = GetNextEvent(minutesOnTheHour);
    string channel = ChannelId;

    SendNotification(title, body, deliverTime, channelId: channel,
        smallIcon: eventIconName, largeIcon: eventLargeIconName);
}

private DateTime GetNextEvent(int minutesOnTheHour) 
{
    DateTime temp = DateTime.Now;

    temp = new DateTime(temp.Year, temp.Month, temp.Day,
        temp.Hour, minutesOnTheHour, 0);

    return temp;
}

This one has the similar structure, but uses a different icon from the Mobile Notification Settings. It also has a helper for the helper: GetNextEvent, which helps translate an amount of time that you want to wait into the specific DateTime format that you need to send to SendNotification.

You can design similar functions to help you achieve any type of notification scheduling you need.

Starting Fresh

There are a couple of last pieces to put the entire puzzle together.

At the bottom of the Notification Manager, add a helper function that calls the retention reminder and event scheduling functions that you want:

void ScheduleCurrentNotifications() 
{
    //1
    RetentionReminderTest(30);
    //2
    RetentionReminderTest(70);
    //3
    RetentionReminderTest(100);

    //4
    EventAlarmTest(DateTime.Now.Minute + 2);
    //5
    EventAlarmTest(DateTime.Now.Minute + 3);
}
  1. Schedule a retention reminder for 30 seconds
  2. Schedule another retention reminder for 70 seconds
  3. Schedule a third retention reminder for 100 seconds
  4. Schedule a specific event for 2 minutes in the future
  5. Schedule another specific event for 3 minutes in the future

There are many scenarios where scheduled notifications need to be replaced or updated. Add a step to the system flow that removes all previously-scheduled notifications. Every time the player launches the app, previously-scheduled notifications should be discarded and replaced with a fresh set of notifications scheduled from the current playdate.

To implement this feature, add this line to the Start section of Notification Manager:

manager.Platform.CancelAllScheduledNotifications();

That was easy.

Finally, call the ScheduleCurrentNotifications function at the bottom of Start of the Notification Manager. The full Start function should look like this:

void Start()
{
    var c1 = new GameNotificationChannel(ChannelId, "Game Alerts", "Game notifications");
    var c2 = new GameNotificationChannel(NewsChannelId, "News", "News and Events");
    var c3 = new GameNotificationChannel(ReminderChannelId, 
        "Reminders", "Reminder notifications");

    manager.Initialize(c1, c2, c3);

    manager.Platform.CancelAllScheduledNotifications();

    ScheduleCurrentNotifications();
}

Save the NotificationManager script – it’s now complete.

Return to the editor to save the project and deploy it to your Android device. The UI buttons should work the same as before, now the additional notifications fire on the device after you load it. Close and open the app to observe which notifications reset over time.

Retention notification displaying on a device

Congratulations! You’ve mastered advanced notifications.

Overusing Notifications

Armed with your new notification skills, you wield great power that comes with great responsibility, as the cliché goes. While notifications are great when used well, it only takes one annoying notification to get the user to turn off ALL notifications coming from your app.

Even important notifications, like reminders for your mother’s birthday, that arrive too often or in the middle of the night can frustrate the user enough to turn off ALL future reminders. So be conservative when selecting and scheduling which notifications to send.

Where to Go From Here?

Great job on completing this tutorial! You can download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

Feel free to tweak the project to your needs and turn it into something that gets you noticed. :]

The Unity Mobile Notifications Package will continue to evolve, so follow the latest updates here: Unity Mobile Notifications Package.

If you’re interested in notifications on iOS, watch our Push Notifications Video Course or read our book, Push Notifications by Tutorials.

I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!

Average Rating

4/5

Add a rating for this content

2 ratings

More like this

Contributors

Comments