Skip to content

Advanced notification settings, additional features🔗

MRGS allows you to work with all the features and novelties in notifications, namely:

  1. Request permission to send notifications at the time you need (on iOS).
  2. Get notification settings of the user.
  3. Work with delivered and scheduled notifications.
  4. Add buttons to notifications and customize their appearance.
  5. Manage notification grouping in IOS 12+, including the summary view and its arguments.
  6. Add attachments to notifications (on IOS 10+).
  7. Add custom sounds to notifications.
  8. The convenient way to turn on and off notifications on the client with just one method call, and we will take care of canceling notifications or invalidating the token (feature is useful for projects with a switch for notifications availability in the settings)
  9. Put the number on the iOS application icon.
  10. Work with Trial notifications on iOS.

Delaying the notification permission request.🔗

In iOS/Android(13+), the first time you request permission to send notifications, the user will be shown a popup. With the standard setting of MRGSNotificationCenter, this popup will be shown at the very start of the application, which can negatively affect the number of permissions, this is bad practice, first it’s better to explain to the user why understanding is needed.

If you need to request permission for the first time from the user later (for example, by pressing a button, or after a certain screen), then you can start our MRGSNotificationCenter at the right time. After launch, permission to send notifications will be requested, a token has been received. To do this, at the parameter configuration step, you must set the deferred start flags to true:

using MRGS;

public class MasterController : MonoBehaviour
{
    void Awake()
    {
        var serviceParams = new MRGServiceParams(MRGS_APP_ID, CLIENT_SECRET);

        serviceParams.IOSExtraOptions.DefferedMRGSNotificationCenterStart = true;
        serviceParams.AndroidExtraOptions.DeferredPushStart = true;

        // Further setup and initialization of MRGS
        // ...
    }
}
    ```

Then, at the moment when you are ready to show the user a request, you need to call the method:

```C#
MRGSNotificationCenter.Instance.EnableMRGSNotifications();

Or other variations of this method (for more details on enabling and disabling notifications, see corresponding section).

After calling the method, our MRGSNotificationCenter will be launched, the popup will be shown. In the future, it is not necessary to call this method every time, we ourselves will automatically run MRGSNotificationCenter at the application start if the popup has been shown at least once.

Alternative request display method

If you have delayed the notification permission request (or need to be shown again on Android as the dialog can be shown multiple times there), you can invoke it later like this:

MRGSNotificationCenter.Instance.RequestNotificationsPermissions();

Working with Trial (Provisional) Notifications on iOS🔗

When you explicitly request permission to send notifications, users must immediately decide whether to allow or deny them before they see notifications from the app. Users may not have enough information to make a decision and may deny authorization. You can use Provisional authorization - then users can first evaluate the notifications, and then decide whether to allow them or not.

The system discreetly delivers Trial notifications - they do not interrupt the user with a sound or banner and do not appear on the lock screen. Instead, they only appear in the Action Center history. Trial notifications also include buttons that prompt the user to leave or turn off the notification.

notifications-ios-trial-notifications

If the user clicks the "Leave" button, the system prompts him to choose between regular or silent notifications. If the user selects regular notifications, your app gets all permissions. If the user chooses to receive silent notifications, the system allows your app to send notifications, but does not allow your app to show alerts, play sounds, or tag a number on the app icon - your notification is only displayed in the notification center history. If the user clicks the Disable button, the system confirms the choice before denying your application authorization to send notifications. Read more in official documentation

To enable this request, you need to call the addExtraPermissionsForNotificationsAuthorizationRequest method. This method should be called before MRGS is initialized at every start, we recommend calling it when setting parameters for starting MRGS. Example:

// MRGService settings
MRGServiceParams serviceParams = new MRGServiceParams(MRGS_APP_ID, CLIENT_SECRET);
// ...

MRGSNotificationCenter.AddExtraPermissionsForNotificationsAuthorizationRequest(MRGSNotificationAuthorizationOptionType.Provisional);

// Further setup and initialization of MRGS
// ...

Since this functionality only works on iOS 12+, it will be ignored by MRGS on versions below. In order to check if the Trial Notifications functionality is available, you can use the method:

MRGSNotificationCenter.IsProvisionalNotificationsRequestAvailable();

Important

When using this permission, MRGS will not pay attention to delayed start, since there is no need to show the user the popup with permission. MRGS will launch its service at the start, and will work as usual, you do not need to add any additional logic.

If you later decide to disable this request, then for old users who have already been requested for Trial Notifications, but they still have not given permission in the notification center, MRGS will continue to request permission for Trial notifications (so as not to unexpectedly show the request for permission).

Enabling or disabling notifications🔗

MRGS allows you to easily enable or disable specific types of notifications on a user's device. This functionality is useful for projects where in the settings there is a switch for notifications availability. So you can control the availability of local and push notifications:

public enum MRGSNotificationsType
{
    All = 1,
    Local = 2,
    Remote = 3,
}

To disable a specific type of notification, you must call the method:

// Pass the notification type to be disabled to the method
MRGSNotificationCenter.Instance.DisableMRGSNotifications(MRGSNotificationsType.Local);

// Or a method that disables all types of notifications
// (equivalent to the call above, i.e. with the MRGSNotificationsType.All parameter):
MRGSNotificationCenter.Instance.DisableMRGSNotifications();

After disabling local notifications, we will clear the current queue of scheduled and delivered notifications, and we will ignore the addition of new local notifications (with an output to the error log) until they are turned on again.

After disabling push notifications, we will send shutdown information to the MRGS server, and the token on the server will be disabled, that is, the notification will not reach the user. As soon as push notifications are turned on again, we will send a valid token to the MRGS server.

To enable a specific type of notifications again, use the method:

// Pass the notification type to be enabled to the method
MRGSNotificationCenter.Instance.EnableMRGSNotifications(MRGSNotificationsType.Local);

// Or a method that enables all types of notifications
// (equivalent to the call above, i.e. with the MRGSNotificationsType.All parameter):
MRGSNotificationCenter.Instance.EnableMRGSNotifications();

To check whether a specific type of notifications is currently enabled (all, local, push), a method is provided:

// Pass the notification type to be checked into the method
bool res = MRGSNotificationCenter.Instance.IsMRGSNotificationsEnabled(MRGSNotificationsType.All);

Thus, you can easily turn on or off a certain type of notification, or both types at once. A small example is given below:

public void Toggle(bool toggleStatus)
{
    if (toggleStatus) 
    {
        // User turned on all notifications
        MRGSNotificationCenter.Instance.EnableMRGSNotifications();
    } 
    else
    {
        // User turned off all notifications
        MRGSNotificationCenter.Instance.DisableMRGSNotifications();
    }
}

Checking the status

These methods enable / disable notifications from the MRGS side, it has nothing to do with the system. We advise check the availability of notifications for the user (described in the section below) when they enable notifications in your application, and if necessary, lead them into the settings app.

Getting user notification settings.🔗

If you need to know the general availability of notifications, then you can use the method that will return TRUE, if the notifications are available:

MRGSNotificationCenter.Instance.IsNotificationsEnabled((bool enabled) =>  {
    if (enabled) 
    {
        // Everything is fine, you can send notifications
    }
    else
    {
        // The user has disabled notifications, you can ask him to turn them back on
    }
});

To get the user settings, use the following method:

MRGSNotificationCenter.Instance.GetUserSettings((MRGSNotificationSettings settings) => {
    Debug.Log("MRGSNotificationSettings - " + settings);
});

The returned object of the MRGSNotificationSettings class contains notification settings, including accessibility, whether banners, sounds, numbers on the application icon and other parameters are enabled (for IOS 10+), you can find the full list of fields in the class description.

Go to settings

If the user has refused notifications in the system window, or turned off the types of notifications you need, but is ready to turn them back on, then you can transfer it directly to the settings application on the tab of your application using using this method

Managing delivered and scheduled notifications.🔗

With MRGS you can:

For scheduled notifications (Not yet delivered, the trigger didn't fire yet):

  1. Find a notification with the specified identifier in the scheduled notifications,
  2. Get a list of all scheduled notifications,
  3. Cancel scheduled notifications with specified identifiers,
  4. Cancel all scheduled notifications.

For all of this, use the methods of the MRGSNotificationCenter class:

void FindPendingNotification(string identifier,Action<MRGSNotification> completion)
void GetPendingNotifications(Action<List<MRGSNotification>> completion)
void RemovePendingNotifications(List<string> identifiersArray)
void RemoveAllPendingNotifications()

Example:

MRGSNotificationCenter.Instance.GetPendingNotifications((List<MRGSNotification> pendingNotifications) =>
{
    foreach (MRGSNotification pendingNotification in pendingNotifications)
    {
        Debug.Log("Pending notification - " + pendingNotification);
    }
});

For a detailed description of methods and parameters, see the class description MRGSNotificationCenter.

For already delivered notifications (will work on iOS 10+):

  1. Find a notification with the specified identifier in the delivered ones,
  2. Get a list of all delivered notifications,
  3. Cancel the delivered notifications with the specified identifiers,
  4. Cancel all delivered notifications.

For all of this, use the following methods:

void FindDeliveredNotification(string identifier,Action<MRGSNotification> completion)
void GetDeliveredNotifications(Action<List<MRGSNotification>> completion)
void RemoveDeliveredNotifications(List<string> identifiersArray)
void RemoveAllDeliveredNotifications()

Only for iOS.

Managing delivered notifications works only for iOS. And only if the resetBadge field is set to false (because otherwise, when the badge is reset, all delivered badges will be deleted). In other cases, null or empty arrays will be returned.

Adding buttons and customizing them🔗

iOS🔗

In order for the system to know which buttons to display, it is necessary to register them.

Registration can't work for individual buttons, but for categories (types) of notifications, which, in turn, contain buttons. When working with MRGS, the classes MRGSNotificationAction and MRGSNotificationCategory are used for registration.

To create a category, use the following method:

// Create buttons, they have an id that will return when clicked, and a display text
var playAction = new MRGSNotificationAction("StartPlayingButton", "Just play!");
var getRewardAction = new MRGSNotificationAction(identifier: "GetRewardButton", title: "Get reward!");
var actionsList = new List<MRGSNotificationAction> { playAction, getRewardAction };

// Create a notification type that contains the two buttons we created earlier and has a unique ID
var categoryOnReturn = new MRGSNotificationCategory("categoryOnReturnNotifications", actionsList);

Then you need to register the created categories:

// Registering an array of created categories
var categoriesList = new List<MRGSNotificationCategory> { categoryOnReturn };
MRGSNotificationCenter.Instance.RegisterCategories(categoriesList);

Warning!

On iOS 9, changes will only take effect next time the application is launched.

To add a notification from a certain category, add the following line when setting up:

notification.IosExtraOptions.CategoryIdentifier = "categoryOnReturnNotifications"; //Category id

If the user clicked the button in the notification, then in the callback that came to you in the MRGSNotification object the notification.IosExtraOptions.DeliveryChosenActionIdentifier field will contain the identifier (transferred when creating the MRGSNotificationAction) of the pressed button.

Custom notification interface.

The custom interface on iOS is implemented using "extensions". You must create this extension in Xcode and draw your custom interface in it. Then, while there, bind the identifier of the category that you registered through MRGS to the extension. Read more in official documentation

Once you've created an extension in XCode, write a script that will add it to the generated project from Unity using PBXProjectExtensions.AddAppExtension

If you encounter the error iOS 14 does not support 32-bit programs, add an architecture exception for the extension target:

project.SetBuildProperty(notificationExtensionTarget, "ARCHS", "$(ARCHS_STANDARD)");
How to send a notification with the specified category from server

See the relevant section in server API documentation

Android🔗

Android Custom Notification1

To use your own layout of notifications on Android, you need to make the following steps:

  • Create a layout in the Android resources. Use the (res/layout) directory.
  • You need to put the images that you want to use inside this markup into the resources (res/drawable).
  • Text can be set directly, or also downloaded from Android resources.

Example:

//animated_notification - the name of the markup file (res/layout/animated_notification.xml)
notification.AndroidExtraOptions.CustomView = "animated_notification";
//notification_icon - the ImageView id inside the markup (<ImageView android:id="@+id/notification_icon">)
//app_icon - the icon in resources (res/drawable/app_icon.png)
notification.AndroidExtraOptions.SetCustomViewImage("notification_icon", "app_icon");
//notification_text1 - the TextView id inside the markup (<TextView android:id="@+id/notification_text1">)
//app_name - string resource (res/values/strings.xml <string name="app_name">Unity</string>)
notification.AndroidExtraOptions.SetCustomViewTextFromRes("notification_text1", "app_name");
//notification_text2 - the TextView id inside the markup (<TextView android:id="@+id/notification_text2">)
//Hello, World - the text is not from the resources for display in the notification
notification.AndroidExtraOptions.SetCustomViewText("notification_text2", "Hello, World!");

notification.AndroidExtraOptions.Icon = "imageName" // File name WITHOUT extension in the directory with resources (res/drawable)
notification.AndroidExtraOptions.LargeIcon = "imageName" // File name WITHOUT extension in the directory with resources (res/drawable)

Managing grouping.🔗

iOS🔗

On iOS 12, all notifications are grouped. If you want to manage the grouping (i.e., split the notification group from your application into, let's say, two or three groups), you need to add the following line when creating a notification:

notification.IosExtraOptions.ThreadIdentifier =@"THREAD_1"; //Select a grouping stream

The choice of the stream identifier is up to you. For example, to have two groups of notifications from an application of the "messenger" type, for each dialogue specify its own ThreadIdentifier.

If you want one notification to be counted as three (by weight) when grouping, and if you want to specify the name of the group, use the following fields:

notification.IosExtraOptions.SummaryArgumentCount = 3;
notification.IosExtraOptions.SummaryArgument = @"MRGSSS";

If you want to choose the format of the explanatory line when grouping, then use the following method when creating a category:

// FORMAT is the format string for grouping
// PHOLDER is text if the user has notifications hidden on the lock screen enabled
MRGSNotificationCategory.Create(identifier: ..., actionsArray: ..., summary: "FORMAT", placeholder: "PHOLDER");

// For example:
var category = new MRGSNotificationCategory("some_id", <list>)
{
    CategorySummaryFormat = "to go",
    HiddenPreviewsBodyPlaceholder = "Some interesting info for you!"
};

Android🔗

By default, Android does not group notifications. If you want to combine several notifications into one, they need have set group Id.

Use the following fields:

notification.AndroidExtraOptions.GroupId = 1
notification.AndroidExtraOptions.GroupMessage = "Hello"
notification.AndroidExtraOptions.GroupTitle = "Some Title"

Adding attachments to notifications. (only on iOS)🔗

To add an attachment (a picture as on the first iOS screenshot), use the following field:

var attachmentsList = new List<string> { "/path/to/image1", "/path/to/image2" };  //Array with paths to attachments
notification.IosExtraOptions.Attachments = attachmentsList;

Paths to the attachments must be set either completely to the resource in the ios format, or you can specify the relative path from the mainBundle, meaning that if the picture is in the root directory of the application, it'll be enough to write:

notification.IosExtraOptions.Attachments = new List<string> {"imageName.png"};

That is, you can set the path to the attachment in two ways:

notification.IosExtraOptions.Attachments = new List<string>(){
    "forest.jpg", // Get from application root bundle
    "file://" + System.IO.Directory.GetParent(Application.dataPath) + "/" + "forest.jpg" // Manually set full path to file (in application root bundle in this example)
};

Setting up the number on the icon. (only on iOS)🔗

Use the following field:

notification.IosExtraOptions.Badge = 3; //Upon delivery, the number on the icon will become 3

Adding custom sounds to notifications.🔗

Please note that the file names for iOS and Android are different.

To add your custom sound that plays when a notification arrives, use the following field:

#if UNITY_IOS
notification.Sound = "CustomNotificationSound.caf"; //Where "***.caf" - the name of the sound file in the resources of the application.
#elif UNITY_ANDROID
notification.Sound = "custom_notification_sound"; //For Android, the file name must be without extension
#endif

On Android 8.0 and higher, there is no way to set the sound for a particular notification. To configure the notification sound, you must specify it when creating a channel.

Where should I put the files?

For iOS, the file must be in the MainBundle of the application, and when setting the Sound value field, it is necessary that the line contains file name and extension, as shown in the example above. For Android, the file should be in the src/main/res/raw/ folder.

Creating channels (Only for Android).🔗

To specify the channel that you're going to use, use the following field:

notification.AndroidExtraOptions.ChannelId = "mrgs_unity" // Channel id
notification.AndroidExtraOptions.ChannelName = "UnityMRGS" // Name of the channel
notification.AndroidExtraOptions.ChannelGroupId = "mrgs_unity_group" // Group that channel belongs to
notification.AndroidExtraOptions.ChannelGroupName = "UnityMRGSGroup" // Name of the group

If the channel has not been previously created, it will be created with the default settings. For fine tuning, such as specifying sound, you must manually set the channel parameters.

  1. Create a group to which the channel will belong:
var notificationGroup = new MRGSNotificationChannelGroup();
notificationGroup.Id = "mrgs_unity_test";
notificationGroup.Name = "MRGS Unity";
MRGSNotificationCenter.Instance.CreateNotificationChannelGroup(notificationGroup);
  1. Create the channel itself:
var notificationChannel = new MRGSNotificationChannel();
notificationChannel.Id = "mrgs_unity_test";
notificationChannel.Name = "MRGS Unity";
notificationChannel.Description = "MRGS Notifications";
notificationChannel.ShouldVibrate = true;
notificationChannel.ShowLights = true;
notificationChannel.Group = "mrgs_unity_test";
notificationChannel.Sound = "custom_notification_sound"; // file name without extension, that you put in the res/raw directory of your Android project

MRGSNotificationCenter.Instance.CreateNotificationChannel(notificationChannel);

Now, when creating notifications, you can specify the ChannelId, ChannelName, ChannelName, ChannelGroupName created by using these methods. In order to use this channel in server push notifications, it is necessary to create it first.

To get a list of channels, you can use the following method:

MRGSNotificationCenter.Instance.GetNotificationChannels()

To delete a channel

MRGSNotificationCenter.Instance.DeleteNotificationChannel("channel_id")

Warning

After deleting a channel, if you create a channel with the same id, the old parameters will be taken into account, not the new ones. Such is Google's policy. It is believed that the user can block or reconfigure the channel and the application should not be able to change these parameters. The only way to "reset" the old channel settings is to delete the application.

Visibility of notifications on LockScreen(secure).(Android only)🔗

If you need additional control over the visibility of notifications on a secure lock screen (which is protected by a password, pin, etc.), you must specify the scope.

// visibility - One of: LockScreenVisibility.Public, LockScreenVisibility.Private, LockScreenVisibility.Secret;
notification.AndroidExtraOptions.Visibility = visibility;

Behavior features

When screen protection is activated, there are several ways to display notifications on the lock screen:

  • Show all notification content
  • Hide sensitive content
  • Don’t show notifications at all

This option allows you to configure global settings for all notifications applications, which can be switched separately for each application in its settings. Starting with Android 8.0, the setting is added for each channel separately.

In addition, when Screen lock and Notification scope are combined, the following behaviors are obtained:

LockScreen with Show all notification content: Public and Private - display notifications on the LockScreen without any restrictions. Secret - doesn't display notifications on LockScreen.

LockScreen with Hide sensitive content: Public - display notifications on the LockScreen without any restrictions. Private - displays the notification but does not display its contents. Secret - doesn't display notifications on LockScreen.

LockScreen with Don’t show notifications at all: No notifications can be shown on the Lock screen.

Keep in mind that the final behavior of notifications on LockScreen depends only on the user.

Setting the number on the application icon on iOS🔗

To do this, you can use the ApplicationIconBadgeNumber property:

MRGSNotificationCenter.Instance.ApplicationIconBadgeNumber = 5;

Control notifications removing at application start. (Android only)🔗

At application start, MRGS removes all are received notifications from notification tray for current application. To change this behavior:

var serviceParams = new MRGServiceParams(appId: "<APP_ID>", appSecret: "<APP_SECRET>")
{
    AndroidExtraOptions =
    {
        ShouldClearNotificationsTray = true
    }
};

Last update: 2023-12-28
Created: 2020-02-17