Using Notifications

From RAD Studio
Jump to: navigation, search

Go Up to Using the RTL in Multi-Device Applications


Notifications are messages that the applications send to communicate information or alert about something.

Note: This topic is about local notifications, which are the notifications that the device applications send; for remote notification see Push Notifications.

RAD Studio provides the TNotificationCenter component to manage multi-device notifications. The notification center, allows you to send messages from running applications. Applications can use the notifications to inform the user about something.

The TNotification component is the message that the application sends to the notification center to be displayed in the designated notification area according to the platform.

You can create notifications for Windows using VCL, or for your Multi-Device applications using FireMonkey.

Notifications Support per Platform

Item Windows macOS iOS Android
Platform Support
Allowed.png

Windows 10 and Windows 8

Allowed.png

10.8+

Allowed.png
Allowed.png
Name of Notification Area Action Center Notification Center Notification Center Notification Drawer
TNotification
TNotification.Name
Allowed.png
Allowed.png
Allowed.png
Allowed.png
TNotification.AlertBody
Allowed.png
Allowed.png
Allowed.png

Mandatory

Allowed.png
TNotification.Title
Allowed.png
Allowed.png

If no title, app name is used as title.

Not supported.

App name used as title.

Allowed.png

If no title, app name is used as title.

TNotification.FireDate Not supported.
Allowed.png
Allowed.png
Allowed.png
TNotification.Number Not supported. Not supported.
Allowed.png

Sets the badge number.

Allowed.png
TNotification.EnableSound
Allowed.png
Allowed.png
Allowed.png
Allowed.png
TNotification.AlertAction Not supported.
Allowed.png
Allowed.png
Not supported.
TNotification.HasAction Not supported.
Allowed.png
Allowed.png
Not supported.
TNotification.RepeatInterval Not supported.
Allowed.png
Allowed.png
Allowed.png
TCustomNotificationCenter
TCustomNotificationCenter.ApplicationIconBadgeNumber Not supported. Not supported.

See OS X Badge Sample.

Allowed.png
Not supported.
TCustomNotificationCenter.ScheduleNotification Not supported.
Allowed.png
Allowed.png
Allowed.png
TCustomNotificationCenter.PresentNotification
Allowed.png
Allowed.png
Allowed.png
Allowed.png

Windows Notifications

Toast notifications are compatible with the following versions of Windows:

  • Windows 8: Windows 8 displays the notifications for a short period of time, after this, the user does not have any further access to the notifications.
  • Windows 10: Windows 10 displays the notifications for a short period of time, after this, the notifications are available in the Action Center.

To access the Action Center to view the notifications, click the Action Center icon available on the taskbar. The icon changes depending on whether there are notifications pending or not:

Windows 10 Action Center Icon
Notifications Pending No Notifications Pending
W10-NotificationsPending.png W10-NoNotificationsPending.png

macOS Notifications

macOS supports notifications since version 10.8. For further information about macOS, see Using the macOS Notification Center.

iOS Notifications

Notification Permissions

To use notifications on iOS, add notification permissions to your application:

  1. Select Project > Options > Version Info.
  2. Select the appropriate iOS target platform.
  3. In the key-value list box, set the value of FMLocalNotificationPermission to True.
FMLocalNotificationPermission.png

Notification Alert

iOS allows the user to set whether the notifications of an app are displayed as a banner or as an alert. Banners are displayed on the screen for a short period of time, while Alerts remain on the screen until the user interacts with the Alert.

To display the notifications as an alert, the end-user has to go to the Notifications Settings of the application in the iOS device, and change the Alert Style when Unlocked settings to Alerts.

Creating Notifications

The TNotification class is used to create notification messages. You need the TNotificationCenter component to manage one or several TNotification instances.

After you have a TNotificationCenter component on your form, you can declare a TNotification variable, and call the CreateNotification method to create the notification.

Delphi:

MyNotification:= NotificationCenter1.CreateNotification;

C++:

TNotification *MyNotification = NotificationCenter1->CreateNotification();

After creating the notification, we recommend that you set at least the following fields:

  • Name: with the unique name to identify your notification.
  • AlertBody: with the text of the notification. The AlertBody field is mandatory in iOS

You can manage other settings for your notifications:

  • Title: with the title of the notification. iOS is not compatible with the Title field; iOS always displays the app name as title.
  • Number: use this field to update the notification number in Android or the application badge number in iOS.
iOS Badge Number Android Notification Number
IOSNotification.PNG Android Notification with number.png

Creating a notification channel

Note: Starting in the 'Android 8.0' release, all 'notifications' must be assigned to a 'notification channel'.

The fallback 'notification channel' is only created in the following cases:

  • The application receives a 'push notification payload' that does not set the 'gcm.notification.android_channel_id' key and you have not set a default 'notification channel id'
  • The application receives a 'push notification payload' that does not set the 'gcm.notification.android_channel_id' key, you have set a default 'notification channel id', but the default 'notification channel' has not been created in the code
  • The application receives a 'push notification payload' that sets the 'gcm.notification.android_channel_id' key, that 'notification channel' has not been created in the code, and you have not set a default 'notification channel id'
  • The application receives a 'push notification payload' that sets the 'gcm.notification.android_channel_id' key, that 'notification channel' has not been created in the code, you have set a default 'notification channel id', but the default 'notification channel' has not been created in the code

‘Notification channels’ manipulation is done through the following methods of the TNotificationCenter class:

function CreateChannel: TChannel; overload;
function CreateChannel(const AId: string; const ATitle: string; const ADescription: string = ''): TChannel; overload;
procedure CreateOrUpdateChannel(const AChannel: TChannel);
procedure DeleteChannel(const AChannelId: string);
procedure GetAllChannels(const AChannels: TChannels);

Creating a custom 'notification channel' and setting it as the default one

Take into account that you do not need to change the 'description' of the fallback 'notification channel', you just need to avoid its creation by following these steps:

1. Creating your custom 'notification channel' in the code:

procedure CreateDefaultNotificationChannel;
var
 NotificationChannel: TChannel;
begin
 NotificationChannel := NotificationCenter.CreateChannel;
 NotificationChannel.Id := 'custom_notification_channel';
 NotificationChannel.Title := 'Custom notification channel';
 NotificationChannel.Description := 'Notification channel used for Firebase';
 NotificationChannel.Importance := TImportance.High; // NOTE: This is a 'heads-up notification'.
 
 NotificationCenter.CreateOrUpdateChannel(NotificationChannel);
end;

2. Setting the default 'notification channel id' in the project options:

  • Click on the 'Project > Options...' menu item
  • Navigate to the 'Application > Services' options page
  • Change the 'Default local notification channel id' to 'custom_notification_channel'
  • Save the changes to the project options

3. Ensuring that the new project options are taking effect:

  • Build and deploy your application
  • Open the generated 'AndroidManifest.xml' file
  • Search for the following 'meta-data' declaration:

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="custom_notification_channel" />

4. Sending 'push notification payloads' to the 'Firebase Cloud Messaging' server:

  • On the Android device...
    • Launch your application
    • Open your testing device's 'Settings' application
    • Tap the 'Apps & notifications' settings item
    • Tap the list item corresponding to your application
    • Tap the 'Notifications' settings item
    • Ensure that 'Custom notification channel' is listed as a 'notification channel'
  • On the Windows host...
    • Send a 'push notification payload' to the 'Firebase Cloud Messaging' server, setting the 'device's registration token'
  • Back on the Android device...
    • Open your testing device's 'Settings' application
    • Tap the 'Apps & notifications' settings item
    • Tap the list item corresponding to your application
    • Tap the 'Notifications' settings item
    • Ensure that 'Notification channel for Firebase' is not listed as a 'notification channel'
Note: To avoid creating the fallback ‘notification channel’ you don’t need to set the ‘notification channel id’ in the ‘push notification payload’ to be able to assign ‘push notifications’ to your default ‘notification channel’.

Creating multiple 'notification channels' and assigning 'push notifications' to them

To create multiple ‘notification channels’ you need to create multiple ‘notification channels’ in the code and set the ‘notification channel id’ in the ‘push notification payload’.

Follow these steps to create multiple 'notification channels' and assign 'push notifications' to them. Below are all the possibilities available to assign 'push notifications' to 'notification channels', either by setting the 'notification channel id' in the 'push notification payload' or by setting the default 'notification channel id' in the project options.

Follow the instructions to create multiple 'notification channels' in the code:

procedure CreateNotificationChannel(const Id: string; const Title: string; const Description: string; Importance: TImportance);
var
 NotificationChannel: TChannel;
begin
 NotificationChannel := NotificationCenter.CreateChannel;
 NotificationChannel.Id := Id;
 NotificationChannel.Title := Title;
 NotificationChannel.Description := Description;
 NotificationChannel.Importance := Importance;
 NotificationCenter.CreateOrUpdateChannel(NotificationChannel);
end;

Follow these steps to send ‘push notification payloads’ to the 'Firebase Cloud Messaging' server:

  1. First, on the Windows host, build and launch your application.
  2. On the Android device:
    1. Open your testing device's 'Settings' application.
    2. Tap the 'Apps & notifications' settings item.
    3. Tap the list item corresponding to your application.
    4. Tap the 'Notifications' settings item.
    5. Make sure that your multiple notification channels are listed.
  3. On the Windows host:
    1. Send a 'push notification payload' to the 'Firebase Cloud Messaging' server, setting the 'device's registration token' and the 'notification channel id'.

Depending on the approach used to send 'push notification payloads' to the 'Firebase Cloud Messaging' server, set the appropriate one:

Once again, on the Android device:

  1. Open your testing device's 'Settings' application
  2. Tap the 'Apps & notifications' settings item
  3. Tap the list item corresponding to your application
  4. Tap the 'Notifications' settings item
  5. Ensure that 'Notification channel for Firebase' is not listed as a 'notification channel'.

Firing Notifications

FireDate is used to set the date and time when the notification is going to be fired.

As regarding the time to fire the notification, you can create two types of notifications.

Immediate Notifications

By default, FireDate is set to Now, so if you do not change the value of FireDate, the notification is fired immediately.

Scheduled Notifications

Notifications can be scheduled to be fired at any time. Set FireDate to the date and time when you want to fire the notification.

Firing Notifications in a Particular Date and Time

You can set that a notification must be fired on a particular date and time. For example, to set a notification to be fired on the 16th of December of 2015 at 5:30 P.M., you could set FireDate like this:

Delphi:

MyNotification.FireDate := EncodeDateTime(2015, 12, 16, 17, 30, 00, 00);

C++:

MyNotification->FireDate = System::Dateutils::EncodeDateTime(2015, 12, 16, 17, 30, 00, 00);

When scheduling notifications to a particular date and time, you must bear in mind that if the FireDate you set has already passed, the notification is fired immediately.

Firing Notifications After a Period of Time

You can set that a notification must be fired after a period of time. For example, to fire the notification in 1 minute and 30 seconds, you can do the following:

Delphi:

MyNotification.FireDate := Now + EncodeTime(0, 1, 30, 0);

C++:

MyNotification->FireDate = Now() + EncodeTime(0, 1, 30, 0);

If a notification is scheduled, and you create another notification with the same name (whether scheduled or not), any previous notification that was scheduled with that same name is overwritten.

Repeating Notifications

You can use RepeatInterval to schedule notifications to repeat after a period of time. You can use one of the interval types that TRepeatInterval defines: None, Second, Minute, Hour, Day, Week, Weekday, Month, Quarter, Year, or Era.

Warning: When you schedule a notification to repeat after a period of time using RepeatInterval, the notification continues repeating even after the application closes; ensure you deal properly with canceling the notifications.

For example, to set a notification to repeat every hour, you could do the following:

Delphi:

MyNotification.RepeatInterval := TRepeatInterval.Hour;

C++:

MyNotification->RepeatInterval = TRepeatInterval::Hour;

Notification Sound

Enabling Notification Sounds

You can enable or disable the sound using EnableSound. By default EnableSound is set to True.

  • In the case of macOS and iOS, even when the sound is enabled, if the application is in the foreground, the notification sound does not play; macOS and iOS play the notification sound when the application is in the background or closed.
  • In the case of Windows, when EnableSound is set to True the notification sound plays; you can disable the sound by switching it to False.

Customizing Notification Sounds

You can customize the sound of your notifications setting SoundName to the sound for your notification.

To add a custom notification sound follow these steps:

  1. Drag and drop the sound file to the name of your project in the Projects Window, and confirm you want to add the file.
  2. Go to Project > Deployment and set the correct remote paths of the file for the different platforms.
    • iOS:.\
  3. Indicate the custom sound name, set SoundName according to the platform.

Delphi:

{$IFDEF IOS}
MyNotification.SoundName := 'nameOfSound.caf';
{$ENDIF}

C++:

#if defined(_PLAT_IOS)
myNotification->SoundName = "nameOfSound.caf";
#endif
Note: According to iOS documentation the sound file should have aiff, wav, or caf file extensions.

Ensure you add the appropriate unit to your project:

Delphi: Add System.IOUtils in the uses clause.

System.IOUtils;

C++: Add System.IOUtils.hpp in the header file .h of your project.

#include <System.IOUtils.hpp>

If the device is unable to find the custom sound that you set in your project, iOS plays the default sound, but the Android does not play any sound.

Notification Actions

Clicking the notifications in macOS, iOS, or Android, brings the application that sent the notification to the front, whether this application is running in the background or closed completely.

There is no particular behavior when the user clicks the notification in Windows.

Adding Notification Actions

You can execute actions when the user clicks a notification. The event OnReceiveLocalNotification is fired when the user clicks a notification. Write an event handler to define an action.

The event handler for the OnReceiveLocalNotification even receives the TNotitication that the user clicked in the ANotification parameter; use the ANotification parameter to get further details about the notification the user clicked.

To show a message according to the notification the user clicked:

Delphi:

if ANotification.Name='ProcessCompleted' then
	ShowMessage('The process is completed.');

C++:

if (ANotification->Name == "ProcessCompleted") {
	ShowMessage("The process is completed.");
}

Notification Actions (macOS and iOS)

You can add an action button to an alert so the user can open the application by clicking the button. For this feature to work, the user needs to set the style of notifications settings of the project to Alerts, for further information see how to set Notification Alerts in macOS and Notifications Alerts in iOS.

To add an action button, set the HasAction field to True. Use the AlertAction field to indicate the text of the button.

Delphi:

MyNotification.HasAction := True;
MyNotification.AlertAction := 'Open App';

C++:

MyNotification->HasAction = True;
MyNotification->AlertAction = "Open App";

Sending Notifications to the Notification Center

After you finish configuring all the settings for your notification, you must send your notification to the notification center to process it.

You can send notifications to the notification center using one of the following two methods.

ScheduleNotification

ScheduleNotification sends a scheduled notification to the notification center. If FireDate is Now, or if FireDate has a past TDateTime, then the notification is presented immediately; otherwise the notification is scheduled as indicated.

Warning: Windows does not support ScheduleNotification.

Delphi:

NotificationCenter1.ScheduleNotification(MyNotification);

C++:

NotificationCenter1->ScheduleNotification(MyNotification);

PresentNotification

PresentNotification presents the notification immediately regardless of the value of FireDate.

Delphi:

NotificationCenter1.PresentNotification(MyNotification);

C++:

NotificationCenter1->PresentNotification(MyNotification);

Cancelling Notifications

You can cancel notifications that are scheduled, notifications that repeat, and you can also remove notifications that are already displayed in the Action Center, Notification Center, or Notification Drawer.

CancelNotification

CancelNotification is used to cancel a scheduled notification or a notification that repeats. You need the Name of a notification to cancel it.

Delphi:

NotificationCenter1.CancelNotification('MyNotificationName');

C++:

NotificationCenter1->CancelNotification("MyNotificationName");

CancelAll

CancelAll cancels all notifications:

  • The notifications that are scheduled will not be fired.
  • The notifications that have repeat intervals are canceled.
  • The notifications that are available in the Action Center, Notification Center, or Notification Drawer for this application are deleted.

Delphi:

NotificationCenter1.CancelAll;

C++:

NotificationCenter1->CancelAll();

Updating Notifications

You can update notifications that are pending to be fired using the Name, which is the unique identifier of the notification. To update a notification, follow these steps:

  1. Create an instance of TNotification with the same Name as the one you want to update.
  2. Configure the new instance with the settings that you want.
  3. Send the notification to the notification center.

Updating future notifications, whether scheduled or with repeat interval, deletes the notifications that are already present Action Center, Notification Center, or Notification Drawer (if any), and overwrites any future notifications.

See Also

Code Samples