16 Notifications
What Can I Do with Notifications?
Notifications can provide the timely awareness of information and events that mobile users seek. Notifications are short, specific, targeted messages sent to a mobile application. The purpose of a notification is usually to tell users that there is new information available. For example, a user who is running a shopping app might get information about an upcoming sale.
You can send these targeted messages either on demand or on a predefined schedule to:
-
a specific device ID or a collection of device IDs (mostly useful for testing)
-
a specific user or a collection of users
-
all users and devices associated with a specific mobile backend
-
devices or users for a given operating system (iOS, Android or Windows)
Note:
Push notifications should not be used to send critical or emergency information, because network delays and other issues can make deliveries untimely. However, for everyday uses like sports scores and upcoming sales, notifications are great.How Are Notifications Sent and Received?
As a mobile application developer, you configure your mobile app to receive notifications over the network. Once your mobile app is configured and installed on a device, it connects to its backend to receive notifications. The steps below summarize the path that a notification takes.
-
You compose a notification, for example, "Hi! Our storewide sale is tomorrow," and define a recipient for it. You can send the notification to a specific user or device or set of users or devices, to everyone in the backend, or to a specific device type (Android, iOS or Windows). You can send the notification immediately or schedule it to be sent at a later date and time. When you POST a notification, an ID is created for the message. You can use this ID to cancel a message if it hasn’t been sent yet.
-
The notification is addressed to the associated device IDs and distributed to the appropriate push networks for delivery.
-
The notification is received by the mobile application, and the owner of the device gets it.
The notification service providers and their payload limits are:-
WNS: 5K
-
FCM: 4K
-
GCM: 4K
-
APNS: 4K
-
SMS: 1000 bytes
-
What is the Device ID or Notification Token?
The device ID, also known as the notification token, uniquely identifies the specific instance of a mobile application associated with a specific device. This ID is used to ensure that notifications are sent to the correct recipient.
A unique device ID is assigned when a mobile app registers a device during the device handshake. After that point, the ID can be used to identify that specific recipient. Multiple instances of the same mobile app on the same device have different device IDs. The device ID changes periodically, but this is handled internally and is transparent to the mobile app.
You can look up the device IDs registered with a mobile app in the Device Registry, from the Notifications page for the associated backend in the UI. To register a specific device ID to be used as a recipient address for notifications, you can use the REST API. Keep in mind that sending a notification directly to a device ID is only useful for testing. There are more efficient ways to send notifications to a specific group of users. For details and examples, see Sending Notifications to and from Your App.
Setting Up a Mobile App for Notifications
Before you begin, you can install the client SDK’s Notifications library to simplify development. The Notifications SDK library can be individually installed into your app, or along with the other mobile client SDK libraries. For details on the SDKs, see The SDKs.
The set up process is different for each platform:
After you complete the set up steps for your platform, you have a few options for sending notifications from MCS to your mobile app. See Sending Notifications to and from Your App.
Now that you have registered the app client in OMCe, you have a few options for sending notifications to your app, as shown in Sending Notifications to and from Your App.
Setting Up Android Notifications
-
First, get credentials from the notification provider to establish your mobile app as a known item on the network. See Android: Google API Key.
-
Create a client for your mobile app in MCS, and configure notifications profile(s) by entering the network credentials you got in step 1. See Client Management.
-
Set up the app to connect to the notification provider from the mobile device and establish rules for communication. See Setting Up a Device Handshake for Android (FCM).
After you complete these steps, you have a few options for sending notifications from MCS to your mobile app. See Sending Notifications to and from Your App.
Android: Google API Key
Note:
When you generate the configuration file for your app, make sure you choose to enable the Cloud Messaging service.FCM Notifications
For FCM notifications, in the Android app’s AndroidManifest.xml file, within the <application>
node, add the following entries:
<service android:name="oracle.cloud.mobile.fcmnotifications.McsRegistrationIntentService" android:exported="false" />
<service android:name="oracle.cloud.mobile.fcmnotifications.MCSFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
The FCM messaging library must be added as a dependent library in the application's build file as described in Set up Firebase and FCM SDK. When generation is complete, the Project Number (aka Sender ID) and server key are displayed. You need these credentials to register the mobile app for notifications in MCS. They are unique to the mobile app and can’t be used to send notifications to any other app. You also need these values to get a registration token from FCM and set up the connection with MCS, as described in Setting Up a Device Handshake for Android (FCM).
GCM Notifications
<application>
node, add the following entries: <service android:name="oracle.cloud.mobile.notifications.McsRegistrationIntentService" android:exported="false" />
<service android:name="oracle.cloud.mobile.notifications.GcmTokenRefreshListenerService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
Google Play Services must be added as a dependent library in the application's build file, or these services will be flagged in error.When generation is complete, the Project Number (aka Sender ID) and legacy server key are displayed. You need these credentials to register the mobile app for notifications in MCS. They are unique to the mobile app and can’t be used to send notifications to any other app. You also need these values to get a registration token from FCM and set up the connection with MCS, as described in Setting Up a Device Handshake for Android (FCM).
Setting Up a Device Handshake for Android (FCM)
This section assumes you have already generated a configuration file for your app. You will need the Sender ID (Project Number) you got when you configured your project, as described in Android: Google API Key.
For FCM Notifications, an Android app needs to extend FirebaseMessagingService
to define a service for receiving Notifications. By overriding the onMessageReceived
method, you can perform actions based on the incoming message. For more information on handling notifications in Android, see Receive Messages on Google FCM Developers.
In your app’s src/main/AndroidManifest.xml
file, just before the closing </application>
tag, register for the Notifications service, as shown below.
<application> ...
<service
android:name="oracle.cloud.mobile.fcmnotifications.MCSFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
Set permissions to receive and display notifications by inserting these entries in the Android manifest (somewhere above the <application>
entry).
<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission
android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application>
To establish communication and register for notifications, here’s what the device handshake might look like in an Android app, using the client SDK:
...
import oracle.cloud.mobile.exception.ServiceProxyException;
import oracle.cloud.mobile.fcmnotifications.Notifications;
import oracle.cloud.mobile.mobilebackend.MobileBackendManager;
public class MainActivity extends Activity {
private Notifications mNotification;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.registerNotificationClient();
}
//method that initializes and returns the Notifications client
private void registerNotificationClient(){
try {
mNotification =
MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Notifications.class);
mNotification.initialize(this);
} catch (ServiceProxyException e) {
e.printStackTrace();
}
}
}
Getting a FCM Registration Token
You also need the Sender ID to register your app with FCM to get a registration token. The registration token is passed to OMCe, which packages it with the notification to tell Google that your app and the device it runs on are legitimate recipients on the network. Google provides the Instance ID API to handle registration tokens. See Set Up a Firebase Cloud Messaging Client App on Android on Google Developers.
public void onClick(View view) {
try {
//Registration process callback
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(NotificationsConfig.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
Logger.debug(TAG, "Token retrieved and sent to server.");
} else {
Logger.debug(TAG, "An error occurred while registering the device");
}
}
};
//call on successful registration
LocalBroadcastManager.getInstance(mCtx).registerReceiver(
mRegistrationBroadcastReceiver,
new IntentFilter(NotificationsConfig.REGISTRATION_COMPLETE));
//Initialization of MCS notifications service
not = MobileBackendManager.getManager().getDefaultMobileBackend
(mCtx).getServiceProxy(Notifications.class);
boolean result = not.initialize(mCtx);
} catch (ServiceProxyException e) {
e.printStackTrace();
}
}
To de-register a device for notifications, here’s what the code might look like in an Android app, using the client SDK:
//Initialization of MCS notifications service
Notifications notifications = MobileManager.getManager().getDefaultMobileBackend(getApplicationContext()).getServiceProxy(Notifications.class);
boolean result = notifications.deregisterDevice(view.getContext());
Logger.debug(TAG, "unregister " + result);
Setting Up a Device Handshake for Android (GCM)
This section assumes you have already generated a configuration file for your app. You will need the Sender ID (Project Number) you got when you configured your project, as described in Android: Google API Key.
In addition to the device handshake, for GCM notifications an Android app needs to extend GcmListenerService
to define a receiver for the Notifications service. By overriding the onMessageReceived
method in the Android SDK, you can perform actions based on the incoming message. See Simple Downstream Messaging on Google Developers.
main/AndroidManifest.xml
file, just before the closing </application>
tag, register service and broadcast receivers for the Notifications service, as shown below. <application>
...
<receiver android:name="oracle.cloud.mobile.notifications.Mcs2GcmListenerService"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="YOUR.PACKAGE.NAME"/>
</intent-filter>
<receiver>
</application>
<application>
entry).<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<permission android:protectionLevel="signature"
android:name=YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<uses-permission android:name="YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<application>
...
import oracle.cloud.mobile.exception.ServiceProxyException;
import oracle.cloud.mobile.mobilebackend.MobileBackendManager;
import oracle.cloud.mobile.notifications.Notifications;
public class MainActivity extends Activity {
private Notifications mNotification;
private final String PROJECT_ID = "PROJECT_ID_COPIED_FROM_GOOGLE_API_CONSOLE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.registerNotificationClient();
...
}
//method that initializes and returns the Notifications client
private void registerNotificationClient(){
try {
mNotification = MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Notifications.class);
mNotification.initialize(this, PROJECT_ID);
} catch (ServiceProxyException e) {
e.printStackTrace();
}
}
...
}
Getting a GCM Registration Token
You also need the Sender ID to register your app with GCM to get a registration token. The registration token is passed to MCS, which packages it with the notification to tell Google that your app and the device it runs on are legitimate recipients on the network.
public void onClick(View view) {
try {
//Registration process callback
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(NotificationsConfig.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
Logger.debug(TAG, "Token retrieved and sent to server!");
} else {
Logger.debug(TAG, "An error occurred while either fetching the InstanceID");
}
}
};
//call on successful registration
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(NotificationsConfig.REGISTRATION_COMPLETE));
//Initialization of notifications service
not = MobileBackendManager.getManager().getDefaultMobileBackend(view.getContext()).getServiceProxy(Notifications.class);
boolean result = not.initialize(view.getContext(), "714568881816");
}
catch (ServiceProxyException e) {
e.printStackTrace();
}
}
After you’ve set up and registered your app, it can send and receive notifications. For details and sample code, see Sending Notifications to and from Your App.
Setting Up iOS Notifications
-
First, get credentials from the notification provider to establish your mobile app as a known item on the network. See iOS: Apple Secure Certificates.
-
Create a client for your mobile app in MCS, and configure notifications profile(s) by entering the network credentials you got in step 1. See Client Management.
-
Set up the app to connect to the notification provider from the mobile device and establish rules for communication. See Setting Up a Device Handshake for iOS.
After you complete these steps, you have a few options for sending notifications from MCS to your mobile app. See Sending Notifications to and from Your App.
iOS: Apple Secure Certificates
Notifications make special use of Apple's network, so Apple wants extra security protections. You need one of the following secure certificates:
-
Apple Push Notification service SSL (Sandbox) certificate for developing and testing your application with notifications while you do development. Sandbox certificates are intended for automated QA environments where devices don’t change often. In most cases, spam filters should be disabled.
-
Apple Push Notification service SSL (Production) certificate for releasing your application to Apple’s App Store. Apple requires this certificate before you can ship your app to the public, but you can wait until your app is finished to get it.
The steps for getting a Sandbox or Production certificate are very similar to the steps you used to get the first secure certificate when you set up your app. This section assumes that you already set up your Apple developer account, got the required secure certificate, and set up an Application ID and a Provisioning Profile.
Setting Up a Device Handshake for iOS
Next, register your mobile app with the associated mobile backend, and enable notifications. SeeRegistering an App as a Client in MCS.
After you’ve registered your app, it can receive notifications from a range of sources. For details and sample code, see Sending Notifications to and from Your App.Setting Up Windows Notifications
-
First, get credentials from the notification provider to establish your mobile app as a known item on the network. See Windows: WNS Credentials or Syniverse: SMS Credentials.
-
Create a client for your mobile app in MCS, and configure notifications profile(s) by entering the network credentials you got in step 1. See Client Management.
-
Set up the app to connect to the notification provider from the mobile device and establish rules for communication. See Setting Up a Device Handshake for Windows.
After you complete these steps, you have a few options for sending notifications from MCS to your mobile app. See Sending Notifications to and from Your App.
Windows: WNS Credentials
-
Client ID (also called the Package SID)
-
Client Secret (also called a secret key)
To get these credentials, register your mobile app in the Windows Store Dashboard, accessible from the Windows Dev Center. For details on WNS, see WNS Overview on MSDN.
You need these credentials to register the mobile app for notifications in MCS. They are unique to the mobile app and can’t be used to send notifications to any other app.
Syniverse: SMS Credentials
To send Short Message Service (SMS) messages using the Syniverse Messaging Service, the first step is to establish a profile on the Syniverse Developer Community, where you subscribe to the service, register your app, and get credentials.
Creating a Profile on the Syniverse Developer Community
-
Go to the Syniverse Developer Community (developer.syniverse.com).
-
Click Sign Up in the top right corner of the site and enter the requested information.
-
If you have an invitation code from a company in the Syniverse Developer Community enter that into "Company invite code" field. If not, ignore this step.
-
Read and accept the Terms of Service.
-
Check the Captcha box and answer the challenges to prove you aren’t a robot.
-
Click Create profile.
-
When the confirmation email arrives, click the link in the email and verify your user credentials.
Subscribing to the Syniverse Messaging Service
To use SMS in your apps using the SMS short code you got from Syniverse, you need to subscribe to the Syniverse Messaging Service.
-
Log in to the Syniverse Developer Community (developer.syniverse.com).
-
Click your user name in the top right corner and select Company. Verify that your accounts have a billing address associated with them.
-
Navigate to Service Offerings > Messaging Offering and click Subscriptions.
-
Click Subscribe and select “Initial account for [Your username]”
-
Read and accept the Terms of Service.
-
Select Confirm.
-
Verify that your account is listed in Subscriptions.
-
-
If you’re using a Syniverse-provisioned public channel to test messages, you also need to add test phone numbers to the associated whitelist. (Whitelisting is only necessary when testing SMS to U.S. or Canada phone numbers and isn’t required for production apps.)
-
Click your user name in the top right corner and select Company.
-
On the Company page, click the Whitelist tab.
-
Click Add phone number and enter your phone number in the ITU-T E.164 format (i.e., +11234567890).
-
Click Send confirmation code to send a randomly generated number to the phone number in a text message.
-
Retrieve the confirmation code from the text message and enter it in the Confirmation code field. Click Add to confirm the phone number whitelist.
-
Verify that your phone number is included in the whitelist table with "Validated" status.
-
Register Your App and Get Credentials
Before messages can be sent through the Syniverse Messaging Service, there must be an application configured in the SDC platform. Once your app is registered, you can generate the required credentials.
-
Log in to the Syniverse Developer Community (developer.syniverse.com).
-
Click Applications.
-
Click New application.
In the dialog:
-
Give your application a name and description and click Save.
-
Click the gear icon next to your app name and select Edit.
-
Click SDC Self Service and make sure all the options are selected.
-
Click Account & APIs and select the "Initial account for [Your username]" from the Account dropdown.
Turn on the following services: Messaging, SDC Gateway Services, Event Subscription Services, Voice & Messaging and Whitelisting Services.
-
Click Save.
-
-
Generate the required credentials:
Setting Up a Device Handshake for Windows
...
using Oracle.Cloud.Mobile.Notifications;
using Windows.Networking.PushNotifications;
namespace MyWindowsApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
//
// First login to MCS
//
var loginDialog = new LoginDialog();
loginDialog.ShowAsync().ContinueWith((task) => RegisterForNotificationsAsync());
}
private async Task RegisterForNotificationsAsync()
{
var backend = ((App)App.Current).Backend;
// Register for Push Notifications
PushNotificationChannel channel =
await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
await backend.GetService<Notifications>().RegisterForNotificationsAsync(channel.Uri);
}
...
}
}
For details on requesting a channel URI and constructing the notification payload, see Windows Push Notification Services (WNS) overview.
Next, register your mobile app with the associated MCS mobile backend, and enable notifications. For detailed instructions, see Registering an App as a Client in MCS in the Mobile Backends chapter.
After you’ve registered your app, it can receive notifications from a range of sources. For details, see Sending Notifications to and from Your App.
Sending Notifications to and from Your App
Once you’ve set up and registered your mobile app, you can start sending notifications and SMS messages.
-
Send notifications and cancel scheduled notifications from the UI, which can be useful for development.
-
Use the Notifications API to send notifications to and from apps and devices all over the place.
You can also check the status of your notifications in the UI or using the Notifications API. For details, see Troubleshooting Notifications.
Testing Notifications from the MCS UI
Cancelling a Scheduled Notification from the UI
Sending Notifications Using the Notifications API
You can call Notifications REST API endpoints directly or use custom code in your mobile app. This section details the REST endpoints. For information on using custom code including examples and sample code, see Accessing the Notifications API from Custom Code in the Calling APIs from Custom Code chapter.
To register a device ID for notifications, you can use the UI or the Notifications Device Registration API as described in Registering a Device ID.
/mobile/system/notifications/notifications
endpoint allows you to send notifications, cancel scheduled notifications, and check the status of sent notifications.
Note:
Calls to this endpoint must include these headers:-
Authorization
: If you’re using basic authentication, this header should include the name and password for a team member with theMobileEnvironment_Notification
role, encoded in Base64. For OAuth, this header should include the access token. If you’re using OAuth, you must also be a team member with theMobileEnvironment_Notification
role. -
Oracle-Mobile-Backend-ID
: If you’re using basic authentication, you must include this header. The mobile backend ID is listed on the Settings tab for the mobile backend. For OAuth, this information is included in the access token.
-
{"payload":""}
A unified payload that includes well-formed JSON for each supported notification provider (Google, Apple, Windows and Syniverse). For details, see Sending a Notification Using a Unified Payload. -
{"template":""}
A reusable payload template with defined parameters, used to create payloads for each supported notification provider. The payload template includes the following optional parameters:title
,body
,badge
,sound
andcustom
. For details, see Sending a Notification Using a Payload Template. -
{"message":""}
A plain-text message string. For details, see Sending a Text Message Notification.
To send notifications to specific recipients, add an argument after the content of the payload:
-
To send to a user or a list of users, add the
users
argument. A user can be defined byfirstname:lastname
or email address. Multiple users are listed as tokens in an array, and there’s no limit on the number. For example:-d '{"message": "Hi! Our storewide sale is tomorrow.", "users": ["bob@acme.com", "sjones@xyz.net", "banana@peelme.com"]}'
-
To send to everyone on the same mobile platform, add the
platform
(IOS, ANDROID, WINDOWS or WEB). For example:-d '{"message": "Hi! Our storewide sale is tomorrow.", "platform": "IOS"}'
-
To send to a specific notification provider, add the
provider
(APNS, GCM or FCM, WNS or SYNIVERSE). For example:-d '{"message": "Hi! Our storewide sale is tomorrow.", "provider": "APNS"}'
-
To send to a specific device ID or a list of device IDs, add the
notificationTokens
argument. Multiple IDs are listed as tokens in an array, and there’s no limit on the number. For example:-d '{"message": "Test of notifications feature.", "notificationTokens": ["2DD2D2-D2DDG44GD-GDGSDFZS3-3-3DFZSDFDS"]}'
sendOn
argument. For example: -d '{"message": "Come to our discount sale today!", "sendOn": "2015-06-15T6:00Z"}'
For further details, including HTTP response status codes and full schemas for the request and response bodies, see the REST APIs for Oracle Mobile Cloud Service.
Registering a Device ID
The Notifications Device Registration API lets you register the device ID of your mobile app, which can then be used as a recipient address for sending notifications. This API can also associate a user with the device ID, so the user name can also be used as a target for notifications.
You can register a device ID (notificationToken
) directly and send notifications directly to that ID. You can also use this API to associate any user with the device ID.
-
POST /mobile/platform/devices/register
-
POST /mobile/platform/devices/deregister
-
The
mobileClient
parameter identifies the client in the backend with three properties:-
id
: The Application ID assigned by the Google or Apple app store. (This is different from the "App-Key".) -
version
: The version of the mobile client that will receive the notifications, currently 1.0. -
platform
: "IOS" or "ANDROID" or "WINDOWS" or "WEB" (all caps)
-
-
The
notificationProvider
parameter defines the service thenotificationToken
is used for: "APNS" or "GCS" or “FCM” or "WNS" or "SYNIVERSE". -
The
notificationToken
parameter defines the token needed by the notification service for sending calls. This token uniquely identifies the specific instance of a mobile app associated with a specific device, and is used to ensure that notifications are sent to the correct recipient. Encode in hexadecimal if necessary. -
The optional
user
parameter associates the device ID with the user name provided. If theuser
parameter isn’t included, the device ID is associated with the user who is logged in during the registration call.Note:
To specify a different user name, the logged in user must be a team member with theMobileEnvironment_Notifications
role. Keep in mind that registering a user name this way doesn’t validate the entry in the Device Registry. If this results in duplicate user names, notifications could be sent to multiple users. It’s up to the app to ensure that user names are unique if that’s a requirement.
MyAppToken
:curl -v
-H "Authorization: Basic VGVzdE1vYmlsZVVzZXIyYzE4YWRiZjMyMDg0ZWZkOWQyODM0NjA1OGNmExampleAuthString="
-H "Oracle-Mobile-Backend-ID: 7cf06198-053e-4311-8186-cae145900d59"
-H "Content-Type:application/json"
-d '{"mobileClient": {"id": "MyClientac3d8baf1aa348b48d80e9b7fd026067","version": "1.0","platform": "IOS"},"notificationProvider":"APNS","notificationToken":"03767dea-29ac-4440-b4f6-75a755845ade","user":"JoeSmith"}'
http://www.fixitfast.com:8080/mobile/platform/devices/register
Connected to fixitfast.com port (10.176.45.198) port 8080 (#0)
Server auth using Basic with user 'lucy'
POST /mobile/platform/devices/register/
Authorization: Basic VGVzdE1vYmlsZVVzZXIyYzE4YWRiZjMyMDg0ZWZkOWQyODM0NjA1OGNmExampleAuthString=
User-Agent: curl/7.33.0
Host: fixitfast.com:8080
Accept: application/json
Content-Type: application/json
Oracle-Mobile-Backend-ID: 7cf06198-053e-4311-8186-cae145900d59
Content-Length: 32
upload completely sent off: 32 out of 32 bytes
HTTP/1.1 201 Created
{
"id": "7cf06198-053e-4311-8186-cae145900d59",
"user": "JoeSmith",
"notificationProvider":"APNS",
"notificationToken":"03767dea-29ac-4440-b4f6-75a755845ade",
"mobileClient": {"id": "MyClientac3d8baf1aa348b48d80e9b7fd026067","version": "1.0","platform": "IOS"},
"modifiedOn": "2016-05-25T14:58:16.373Z"
}
Sending a Text Message Notification
The example below uses the Notifications REST API to send a simple notification to everyone in the mobile backend. As noted above, the name and password sent in the Authorization
header must be a team member with the necessary permissions.
curl -X POST
-H "Authorization: basic bWNzOldlbGNvbWUxKg=="
-H "Accept: application/json"
-H "Content-Type: application/json; charset=UTF-8"
-H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d"
-d '{"message": "Hi! Our storewide sale is tomorrow."}'
http://www.FixItFast.com:8080/mobile/system/notifications/notifications/
If the notification is sent successfully, the response might look like the example below. The body will be the JSON for the created notification.
Connected to FixItFast.com port (10.176.45.198) port 8080 (#0)
Server auth using Basic with user 'lucy'
POST /mobile/system/notifications/notifications/ HTTP/1.1
Authorization: Basic bWNzOldlbGNvbWUxKg==
User-Agent: curl/7.33.0
Host: newclothes.com:8080
Accept: application/json
Content-Type: application/json; charset=UTF-8
Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d
HTTP/1.1 201 Created
You could also get a status code of 400
(bad request) or 401
(unauthorized).
Sending a Notification Using a Unified Payload
services
property:
-
The
apns
payload must conform to APNS requirements. -
The
gcm
orfcm
payload can contain arbitrary JSON properties. -
The
wns
payload property must contain a well-formedWNS payload
. -
The
syniverse
payload property should contain the string to send as a SMS message.
Note:
The payload template allows you to send provider-specific payloads without defining the code. For details, see Sending a Notification Using a Payload Template.The following are simple examples that define payloads for FCM. An FCM object can contain either a notification object or a data object. A notification object has a predefined set of user-visible keys described in the FCM documentation. A data object has custom key-value pairs.
{"notificationTokens": [ "xxxxx"],"payload": {"services": {"fcm": {"notification": {"title": "Sale On Now!","body": "50% off until Saturday"
}
}
}
}
}
Data object:
"notificationTokens": [ "xxxxxx"],"payload": {"services": {"fcm": {"data": {"acme1": "value1","acme2": "value2"
}
}
}
}
}
Sending a Notification Using a Payload Template
Parameter | Description | Data Type | Example |
---|---|---|---|
title |
The alert title. If a title is specified, the body parameter is also required.
|
string | "Sale On Now!" |
body |
The alert body.
If only a |
string | "50% off until Saturday" |
badge |
A number to badge the notification with.
Android applications don’t support badging, so the number is not passed in the payload. If there is a requirement to pass the "badge" value, it can be passed as part of a custom data payload. |
number | 43 |
sound |
The sound file to play with the notification. Only .wav format is supported by APNS , WNS, and FCM.
|
string | "alert.wav" |
custom |
Any required custom data. | object |
|
The example below shows a notification sent using FCM that includes all five parameters and the resulting payload. An FCM object can contain either a notification object or a data object. A notification object has a predefined set of user-visible keys described in the FCM documentation. A data object has custom key-value pairs.
{
"template": {
"name" : "#default",
"parameters": {
"title":"this is the title",
"body":"this is the body",
"sound":"alert.wav",
"badge": 5,
"custom":
{ "key1": "value1", "key2": "value2", "key3": [ "value3.1", "value3.2"] }
}
},
This payload is delivered in the same way as the following unified payload. As noted above, Android apps don’t support badging, so your app can use the badge
value in other ways. Note that in this example, value is a string, so the value for key3 is converted to a string.
"fcm": {
"notification":
{ "title": "this is the title", "body": "this is the body", "sound": "alert.wav" }
"data":
{ "key1": "value1", "key2": "value2", "key3": "[ \"value3.1\", \"value3.2\"]" }
}
Cancelling Scheduled Notifications
/mobile/system/notifications/notifications/{id}
with the ID assigned to the notification you want to cancel. For this example, the notification ID is 113455
.
curl -X DELETE
-H "Authorization: Basic bWNzOldlbGNvbWUxKg=="
-H "Oracle-Mobile-Backend-ID:1d97542d-51d6-4f18-897f-35053cfdfd2d"
-H "Accept: application/json"
-H "Content-Type: application/json; charset=UTF-8"
http://www.fixitfast.com:8080/mobile/system/notifications/notifications/113455
Troubleshooting Notifications
Sending a notification is an asynchronous process. Once you send a notification, it can sit for minutes, hours, or maybe even days on an Apple, Google or Microsoft server before it gets delivered to the mobile device. Even if a notification can’t be delivered, there might be no error message returned. You have no control over a notification once it gets sent, but these are some common notification problems:
-
A secure certificate is missing, expired, or not located in the right place.
-
The network credentials for the device don't match the credentials registered.
-
A security identifier used in your code doesn’t match the identifier registered with Google, Apple or Windows, or match what’s defined in your Android manifest or iOS Xcode project.
-
The wrong identifier has been entered into a form. For example, when you register for notifications in a backend and it asks you for an API Key, you entered the application key instead.
-
An APNS mismatch between production/development flag and certificate, for example uploading a production certificate but configuring the client saying it's a development certificate.
-
In FCM and GCM, the wrong API key or Project Number/Sender ID means the user might have disabled notifications on their device.
-
The most likely is that the token has expired. A device token lasts between 30 and 90 days depending on the provider. A mobile app should reregister the notifications token every time the app starts up with both MCS and the notifications provider to refresh it.
-
The user deleted the app from their device
-
The API key or certificate in MCS has gone bad by either expiring, or a new API key or certificate was requested from Google/Apple and not uploaded.
-
The user has reinstalled/updated their OS and hasn’t run the app since reloading the OS.
-
The token was mangled somehow during registration.
Checking Notification Status in the UI
Check the History pane, accessible from the Notifications page for your mobile backend, to find out if your notifications were successfully sent.
Scheduled notifications are displayed in the Scheduled tab. To see a list of sent notifications, click the Sent tab. If you don’t see the notifications you expect, click Check for Updates.
The status you see in the History pane reflects the success rate of the notifications that have been sent. You can quickly tell the status of each notification in the History pane by the color in the left column:
-
Green means that more than 70% of individual notifications in the batch were accepted by the Apple and/or Google networks.
-
Yellow means that less than 70% of individual notifications in the batch were accepted.
-
Red means that the batch failed to send successfully from MCS. In most cases, there is a configuration error that needs to be fixed. See Troubleshooting Notifications.
-
Blue means a batch of notifications is currently being sent. In most cases, a Blue indicator appears for only a few moments.
Given the large the number of recipients sent to a popular mobile application, there will never be 100% success. For example, if a notification is directed to a user that has recently lost her phone, the Apple or Google network won’t accept the notification for delivery to the device. The default warning threshold is 70%, but you can change it in the Notifications_DeviceCountWarningThreshold
environment policy.
The Device Manager, also accessible from the Notifications page for your mobile backend, lists all registered devices for the mobile backend with their device IDs/notification tokens. If you don’t see your device, the network provider might have specified that the device ID/notification token is invalid and should be deregistered. Also, if a device hasn’t been reregistered in 60 days, it will be removed from the registry. You can click Clear Registry to remove all registered devices from a mobile backend to facilitate troubleshooting.
You can always look at the MCS logs to see if more information about a notification or batch of notifications is available. Click to open the side menu and select Administration > Logs. For details on the diagnostics tools available through MCS, see Diagnostics.
Checking Notification Status with the Notifications REST API
GET
to mobile/system/notifications/notifications
with the ID of the notification or using the status=
query parameter. You can check for any notification status: New
, Scheduled
, Sending
, Error
, Warning
, or Sent
. (The notification must have been successfully sent.)
curl -i
-X GET
-u team.user@example.com:Welcome1!
-H "Oracle-Mobile-Backend-ID: ABCD9278-091f-41aa-9cb2-184bd0586fce"
http://fif.cloud.oracle.com/mobile/system/notifications/notifications/?status=Scheduled
limit=100&offset=400
would return notifications 400-499.{
"items": [
{
"id": 1234,
"tag": "Marketing",
"message": "This is the alert message.",
"status": "Sent",
"notificationTokens": ["APNSdeviceToken"],
"createdOn": "2014-04-02T12:34:56.789Z",
"platformCounts": [
{
"platform": "IOS",
"deviceCount": 1,
"successCount": 1
}
],
"links": [
{
"rel": "canonical",
"href": "/notifications/1234"
},
{
"rel": "self",
"href": "/notifications/1234"
}
]
},
{
"id": 1235,
"tag": "System",
"message": "Update required.",
"status": "Sent",
"processedOn": "2014-04-01T12:34:56.789Z",
"notificationTokens": ["APNSdeviceToken"],
"platformCounts": [
{
"platform": "IOS",
"deviceCount": 1,
"successCount": 1
}
],
"createdOn": "2014-04-03T58:24:12.345Z",
"links": [
{
"rel": "canonical",
"href": "/notifications/1235"
},
{
"rel": "self",
"href": "/notifications/1235"
}
]
}
],
"hasMore": false
"links": [
{
"rel": "canonical",
"href": "/notifications?offset=0&limit=2"
},
{
"rel": "self",
"href": "/notifications?offset=0&limit=1000"
}
]
}