Notifications

Cascades provides notification APIs that you can use to create notifications and alerts to inform users about application-specific events, such as new emails or meeting reminders. Cascades notifications can be used with the notification settings on a BlackBerry device to highlight an event in your app in the BlackBerry Hub or to add the splat icon to your app’s icon on the home screen. Users can decide whether they want to receive LED, sound, or vibration notifications by customizing the notification settings for your app on the device. For more information about how to use notifications effectively, see the UI guidelines for notifications.

If you want to display a dialog box in your app while your app is in the foreground, you should use the Dialog class or SystemDialog class. For more information, see Dialog boxes, prompts, and toasts and UI guidelines for dialog boxes and toasts.

Notifications should be used only in combination with push notifications implemented using the Push Service or when your app is running in the background. To learn more about the Push Service and creating a push-enabled app, see Push Service and Handling notifications in the BlackBerry Hub.

Sometimes your app needs to notify the user that an event occurred, but the user doesn't need to respond. For example, your app can let the user know that a new email arrived. You can use a blinking LED, a vibration, or a combination of these notifications.

You can use a Notification to notify the user of this type of event.

Certain time-critical events require the user to respond to the notification after it is viewed.

You can use a dialog box for this type of notification. For example, your app might detect that the battery power level is too low and you want your user to decide whether to continue. In this case, you can use a NotificationDialog.

Screen showing the splat icon on the Active Frame image for BBM.

You can also time your notification so that it appears when a certain event happens. For example, you can use a notification to tell a user that a movie rental period is expired. Or you can offer a promotion for users to purchase new levels in your game and set the offer to expire after one week.

Cascades uses four classes to interact with the notification service on your device programmatically: Notification, NotificationDialog, NotificationResult, and NotificationError. Signals are emitted when an error occurs or if the properties of the notification change. To find out more about signals, see Signals and slots.

Settings and types 10.2

Every app has notification settings that the user sets on the System Settings screen on the device. The user can set notification settings at a device level (global notification settings) or customize notification settings for each application (application notification settings). The notification service uses both of these types of settings to determine which notification effect to trigger. An effect can be playing a sound, vibrating the device, flashing the LED, creating an instant preview, and so on.

Notification settings are represented by policies. These policies determine which effects to trigger on the device,

The notification service uses a combination of global notification settings and application notification settings to decide how to trigger a notification. Generally, if the global setting for a notification effect is set to allow, then an application setting can override the global setting (that is, set the notification effect to deny). If the global setting for a notification effect is set to deny, then the application setting has no effect.

You can use the following classes to access notification settings for your app:

  • NotificationApplicationSettings: You can use this class to get the notification settings that the user set for your app. You can't change the settings with this class, but you can use the signals to learn whether the user has changed any notification settings for your app.

  • NotificationDefaultApplicationSettings: You can use this class to change the default notification settings that the notification service sets for your app. If you don't change the initial settings, the default values set by the notification service are used and you can't change them in your app. For more information, see Instant previews 10.2.

  • NotificationGlobalSettings: You can use this class to change the global notification settings. Because these settings apply to all apps running on the device, your app must add the access_notify_settings_control permission to your bar-descriptor.xml file. If the user doesn't grant this permission to your app, your app can't change the global notification settings. You can handle this case in your app. For more information, see Handling ungranted permissions.

  • NotificationSettingsError: This class defines the errors that you can receive when you try to update the default application notification settings or the global notification settings.

Global and application notification settings apply to all notifications created by your app. You can also use the Notification::type property to override global or application notification settings for a single notification. The Notification::type property is defined using the NotificationType enumeration.

Here's how to use the Notification:type property in QML::

Notification {
    id: alert
    title: "This is the title"
    body: "This is the body of the notification"
    type: NotificationType.AllAlertsOff
}

Here's how to use the Notification:type property in C++:

Notification* pNotification = new Notification();
pNotification->setType(NotificationType::Default);
pNotification->setTitle("Hey Listen!");
pNotification->setBody("This is important information.");
pNotification->setType(NotificationType::AllAlertsOff);
pNotification->notify();

The user might set notification settings that don't allow your app to display notifications. You can handle this case by opening the notification settings card. For more information, see App integration and Settings.

Policies and modes 10.2

You can use the following enumerations to set notification settings:

  • NotificationMode: This enumeration defines the possible modes for notification settings. The notification mode groups the policies for each notification effect so that the user can quickly set their global notifications. For example, if the mode is set to Silent, all sound and vibration effects are turned off, including the keyboard and camera sounds. The user sets these values in the Notifications settings on the device. You can set the mode of global notification settings in your app by using the setMode() function.

  • NotificationPolicy: This enumeration defines the possible policy values that you can set for a default notification setting or a global notification setting. For example, you can use the setLed() function to set the policy to Allow so that the notification system triggers the LED flashing effect.

  • NotificationPriorityPolicy: This enumeration defines the notification priority policy values, such as Allow and Deny.

Prerequisites

To use Notifications classes in your app, you must add the following line to the .pro file in your project:

LIBS += -lbbplatform

Your app must also specify the post_notification Post Notifications (post_notification) permission in the bar-descriptor.xml file for your app.

To use notifications in a QML project, you must import the bb.platform library.

import bb.platform 1.0

To use notifications in a C++ project, you must include the following classes in your app header file. It's also a good idea to use the bb::platform namespace so that you don't need to use fully qualified class names in your code.

#include <bb/platform/Notification>
#include <bb/platform/NotificationDialog>
#include <bb/platform/NotificationError>
#include <bb/platform/NotificationResult>

using namespace bb::platform;

Simple notifications

A Notification contains the content of the notification, such as the title, body, and soundUrl.

A Notification also has a key. The key represents the unique identifier of a notification.

Because notifications remain in the BlackBerry Hub even after a user closes your app, you can use the key to clear the notifications after your app is stopped.

One way to set up a Notification is to attach it to a Container in your app as an attached object.

Screen showing a notification in the BlackBerry Hub.

You can use the soundUrl property to specify a unique sound for your app's notification. You can specify the soundUrl as a file URI to a public asset or shared asset on the device. You can set a local asset to be a public asset in the Assets tab of the bar-descriptor.xml file of your project. For more information about referencing shared files in your app, see File system access. You must also set the access_shared permission in your bar-descriptor.xml file for your app to access shared files. For more information about setting permissions, see App permissions.

If you supply a title, notifications appear in the BlackBerry Hub. If you don't supply a title, a new item indicator is displayed on the application icon. The user controls LED, sound, and vibration notifications by using notification settings. By default, sound and vibration notifications are turned off, but if your app triggers a notification that is displayed in the BlackBerry Hub, the LED notification is turned on.

Creating a notification in QML

You can create a Notification, attach it to a Container using UiObject::attachedObjects, and use the notify() function to display it. You can set the properties of the Notification to customize it.

The following code sample creates a UI with two Button controls for creating and clearing a notification. In the code sample, the title and body of the notification are set using text input from the UI.

If you use a specific sound for a notification, the user can't customize the sound through notification settings. Try to use a specific sound only for exceptional circumstances (for example, if your app triggers a special event that needs to be emphasized over other notifications on the device).

import bb.cascades 1.0
import bb.platform 1.0

Page {
    Container {
        attachedObjects: [
            Notification {
                id: alert
                onTitleChanged: {
                    console.log(value);
                }
            }
        ]
        layout: DockLayout {
        }
        Container {
            verticalAlignment: VerticalAlignment.Center
            horizontalAlignment: HorizontalAlignment.Center
            TextField {
                id: title
                hintText: "Title"
                text: "title"
            }
            TextField {
                id: body
                hintText: "Body"
                text: "body"
            }
            Button {
                text: "Fire the Notification!"
                onClicked: {
                    alert.title = title.text;
                    alert.body = body.text;
                    alert.soundUrl = 
                        "file:///<path to public folder>/mysound.wav"
                    alert.notify();
                }
                horizontalAlignment: HorizontalAlignment.Center
            }
            Button {
                text: "Kill the Notification!"
                onClicked: {
                    alert.clearEffects();
                    alert.deleteFromInbox();
                }
                horizontalAlignment: HorizontalAlignment.Center
            } // end Button
        } // Container
    } // Container with attachedObjects
} // Page

Creating a notification in C++

You can also create and display a Notification in C++ as follows:

Notification* pNotification = new Notification();

pNotification->setTitle("My Notification");
pNotification->setBody("This is important information.");

pNotification->notify();

Clearing a notification

You can clear the effects of the current notification by using clearEffects(). You can clear the effects of a specific notification by using clearEffects(const QString) and passing in the key of a specific notification.

You can also delete all your notifications from the BlackBerry Hub by using deleteFromInbox() or deleteAllFromInbox().

You can add a button to your UI to allow the user to clear all notifications. For example, you can use the following code sample in QML:

            
Button {
    horizontalAlignment: HorizontalAlignment.Center
    topMargin: 50

    text: qsTr("Clear All Notifications")
    onClicked: {
        notification.clearEffectsForAll();
        notification.deleteFromInbox();
    }
}

To clear all the effects of a Notification in C++, you can use the following code sample:

Notification* pNotification = new Notification();
pNotification->clearEffects();

The Notification class inherits from the QObject class, so notifications are deleted with their parent. If you don't need a notification anymore, you can call Notification::deleteLater(), which deletes the notification when the system has an opportunity.

You still need to process errors using NotificationError. An error might occur when the notification service can't respond to the request for a notification and sends your app data that isn't valid.

Instant previews 10.2

You can use the notification settings APIs to change the notifications behavior of your app. For more information, see Settings and types.

By default, instant previews are disabled for apps unless the app has an account in the BlackBerry Hub.

In addition to the prerequisites, your app must also specify the access_notify_settings_control permission in the bar-descriptor.xml file for your app. To learn more about the bar-descriptor.xml file, see The bar-descriptor.xml file. To learn more about permissions, see App permissions.

Screen showing an instant preview when the app is running in the background.

To turn on instant previews, you can change the NotificationDefaultApplicationSettings in your app. These settings should be set in your app's constructor because they must be changed before you create any notifications.

For example, you can add the following code to applicationui.cpp:

// Set the default notification settings to allow instant previews
bb::platform::NotificationDefaultApplicationSettings settings;
settings.setPreview(bb::platform::NotificationPriorityPolicy::Allow);
settings.apply();

An application can change these settings only once.

The app must be in the background for an instant preview to be displayed. If the app is in the foreground, the preview doesn't appear. Here's a code sample that triggers a notification when the asleep() signal is emitted.

import bb.cascades 1.2
import bb.platform 1.2

Page {
    Container {
        attachedObjects: [

            Notification {
                id: alert
                onTitleChanged: {
                    console.log(value);
                }
            }
        ]
        TextField {
            id: appLabel
            text: "Hello World"
            textStyle.base: SystemDefaults.TextStyles.BigText
        }
    }
    onCreationCompleted: {
        Application.asleep.connect(onAsleep)
    }
    function onAsleep() {
        alert.title = "Shutting down";
        alert.body = "Saving battery by going to sleep.";
        alert.notify();        
    }
}

To run your app in the background, you can also create a headless part of your app. To learn how to create a headless app from start to finish, see Creating a headless app. When a headless app needs to let the user know that a particular event has occurred, the app sends a notification to the user. These notifications can trigger instant previews. For more information, see Handling notifications.

Notification dialog boxes

Using a NotificationDialog creates a poor user experience because it is disruptive to the flow of your app. Try to use a Notification in your app instead.

You can use a NotificationDialog to display a dialog box when an urgent event occurs. A NotificationDialog contains the same content as a Notification with more properties for displaying the dialog box.

You can use the repeat property to specify that the notification should be repeated, and you can use the buttons property to specify the buttons that the user must tap to dismiss the NotificationDialog.

You must add at least one button to a NotificationDialog.

Screen showing an intrusive notification dialog box.

A NotificationDialog does not add a new item indicator on any app icons. For urgent notifications, you should use a NotificationDialog, and for less time-critical notifications, you should use the new item indicator or notifications in the BlackBerry Hub. When you use a NotificationDialog in your app, the dialog box should convey enough information for the user to act on.

A NotificationDialog uses the show() function to display a dialog box. When a user taps a button, the finished() signal is emitted and you can use the buttonSelection() function to determine which button was tapped.

Creating a notification dialog box in QML

If you want to use a NotificationDialog in QML, you need to import the bb.system library. You can import the bb.system library in your QML file using import bb.system 1.0.

Here's a QML code sample that demonstrates how to create a NotificationDialog:

import bb.cascades 1.0
import bb.platform 1.0
import bb.system 1.0

Page {
    Container {

        layout: DockLayout {
        }
        
        attachedObjects: [
            NotificationDialog {
                id: alertdialog
                title: "A notification dialog box"
                body: "Text displayed in the body of the dialog box."
                repeat: true
                soundUrl: "file:///<public folder>/mysound.wav"
                buttons: [
                    SystemUiButton {
                        label: "Okay"
                    }
                ]
            }
        ]

    	Button {
            text: "Fire the Notification!"
            onClicked: {
                alertdialog.show();
            }
            verticalAlignment: VerticalAlignment.Top
            horizontalAlignment: HorizontalAlignment.Center
        }
    	
        Button {
            text: "Kill the Notification!"
            onClicked: {
                 alertdialog.cancel();
            }
            verticalAlignment: VerticalAlignment.Bottom
            horizontalAlignment: HorizontalAlignment.Center
        } // end Button
    }
}

Creating a notification dialog box in C++

You can also create a NotificationDialog in C++:

void NotificationApp::onButtonClicked()
{
	m_pLabel->setText("");

	NotificationDialog* pNotification = new NotificationDialog();

	pNotification->setTitle("Calendar Notification");
	pNotification->setBody("Budget Meeting");

	pNotification
        ->appendButton(new bb::system::SystemUiButton("Open"));
	pNotification
        ->appendButton(new bb::system::SystemUiButton("Snooze"));
	pNotification
        ->appendButton(new bb::system::SystemUiButton("Dismiss"));

	bool success = QObject::connect(pNotification, 
         SIGNAL(finished(NotificationResult::ButtonSelection*)),
         this, 
         SLOT(onSelected(:NotificationResult::ButtonSelection*)));

    if (success) {
       // Signal was successfully connected.
	   // Now show the notification dialog box in your UI

	   pNotification->show();
    } else {
       // Failed to connect to signal.
       // This is not normal in most cases and can be a 
       // critical situation for your app! Make sure you 
       // know exactly why this has happened. Add some code
       // to recover from the lost connection below this line.
    }
}

Related resources

Design guidelines

Sample apps

 

Last modified: 2014-09-30



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus