8 Notifications

Oracle Mobile Hub provides a Notifications API to simplify sending notifications to devices running your mobile apps. As a mobile app developer, you can set up your mobile applications for notifications and use the Notifications API to send notifications. As a service developer, you can add implementation code to your custom APIs to trigger 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)

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.

Set Up a Mobile App for Notifications

To make notifications work in your mobile apps, there are several key steps.

  1. Install the client SDK for your platform.

  2. Get credentials from notification providers to establish your mobile app as a known item on the network. For detailed instructions, see Get Network Credentials for Notifications.

  3. Create notifications profiles to hold the credentials, described in Create a Notifications Profile.

Next, you need to register an app client and add the notifications profile to it:
  1. Copy the bundle ID (for iOS), package name (for Android), or application ID (for Windows) so that you have it ready when creating the client.

    Once you create a client, you can’t change this value, and the value needs to match that of the profile that you associate with the client.

  2. Click icon to open the side menu to open the side menu and select Development > Notification Profiles.

  3. Click Clients.

  4. Click New Client.

  5. In the New Client dialog:

    • Fill in the Client Display Name and Client Name.

      These can be whatever names that will help you identify the client. The former can have spaces and the latter can’t.

      In most places in the user interface, the client display name is used. The client name is used for clients in packages and the trash.

    • Select the Platform (iOS, Android, Windows, or Web).

    • Fill in the Version Number field.

      This version must match the version number of the app as registered with your platform vendor.

    • Fill in the fully-qualified app ID. You get this from the platform vendor.

      For Apple, it is the Bundle ID assigned to the application in the Xcode project.

      For Google, it is the Package Name for the application as declared in its manifest file.

      For Microsoft, it is the Application ID you gave your app when you registered it in the Windows Dashboard.

      For Web, it can be any unique identifier that distinguishes it from other web applications that you register.

  6. Click Create.

  7. On the Settings page, select a mobile backend to associate with the client from the Mobile Backend dropdown.

  8. Click the Profiles tab and select one or more notifications profiles that you want to associate with the client.

    If the notifications profile is for the notifications service of the app’s vendor (e.g. APNS for an iOS app or FCM for an Android app), the app ID (bundle ID for iOS, package name for Android, or package SID for Microsoft) for the profile must match the app ID specified for the client. A client can only be associated with a single SMS profile.

The next step is to set up the app to connect to the notification provider from the mobile device and establish rules for communication.

Set Up the Device Handshake for Notifications

To allow notifications to be delivered to your mobile app through the network, every platform requires some form of “device handshake” to register and establish the protocol for communication.

Set 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.MobileManager;

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 = 
MobileManager.getManager().getMobileBackend(this).getServiceProxy(Notifications.class);
		  mNotification.initialize(this);
	  } catch (ServiceProxyException e) {
			e.printStackTrace();
	  }
}
}

Get 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 the service, 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.

To set up a callback on successful registration, you could add code like the example below:

public void onClick(View view) {
  try {
    //Registration process callback
	BroadcastReceiver 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! App can use FCM");
}else{ 
		Logger.debug(TAG, "An error occurred while registering the device"); 
		}
	}
};
//Call on successful registration
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
		mRegistrationBroadcastReceiver,
		new IntentFilter(NotificationsConfig.REGISTRATION_COMPLETE));

//Initialization of notifications service
Notifications notifications = 			
MobileBackendManager.getManager().getDefaultMobileBackend(getApplicationContext()).getServiceProxy(Notifications.class);
boolean result = notifications.initialize(view.getContext());
After you’ve set up and registered your app, it can send and receive notifications. For details and sample code, see the chapter Sending Notifications to and from Your App.
De-Registering a Device

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 notifications service
Notifications notifications = MobileManager.getManager().getDefaultMobileBackend(getApplicationContext()).getServiceProxy(Notifications.class);
boolean result = notifications.deregisterDevice(view.getContext());

Logger.debug(TAG, "unregister " + result);
Set Up a Device Handshake for iOS
As an iOS developer, to make a device handshake happen you need to add this code to your Xcode project to get a device token, get a notifications object, and register your app for notifications:
Note that the registration code should be called each time the app starts.
  1. Get a device token from Apple.
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
    	//use registerUserNotificationSettings for iOS 8 and later
    	UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForType:(UIUserNotificationTypeBadge
    				|UIUserNotificationTypeSound
    				|UIUserNotificationTypeAlert) categories:nil];
    	[application registerUserNotificationSettings:settings];
    } else {
    	//We expect deprecation warnings here - this is for iOS 7.1 or before
    	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
    	(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }	

    After calling the above lines of code, the Apple Push Notification Service (APNS) will call one of the delegate methods based on the success or failure to retrieve the device token. If successful, one of the following methods is called: didRegisterUserNotificationSettings: (iOS 8 or later) or didRegisterForRemoteNotificationsWithDeviceToken: (iOS 7.1). In case of an error, the didFailToRegisterForRemoteNotificationsWithEffor: method is called.

  2. Get the Notifications SDK object.
    (OMCNotifications *) getOMCNotifications{
       OMCAuthorization *auth = [[[OMCMobileManager sharedManager] mobileBackend] mobileBackendForName:
         <Name_of_Mobile_Backend_from_OMC.Plist>].authorization;
       OMCNotifications* omcNOtifications=nil;
       NSError* err = [auth authenticate:<Username> password:<Password>];
       if (!err){
          omcNotifications = [[[OMCMobileManager sharedManager] mobileBackendForName:
             <Name_of_Mobile_Backend_from_OMC.Plist>] notifications];
       }
       return omcNotifications;
    }
    
  3. Register for notifications using the Notifications SDK object.
    -(void) registerForMCSNotifications:(id) sender {
        // Get notifications object from your mobile backend object.
         OMCNotifications* notifications = [mbe notifications];
        
        // Call the register api and pass your iOS device's device token data.
        [notifications registerForNotifications:[self getDeviceTokenData]
                onSuccess:^(NSHTTPURLResponse *response) {
                  NSLog(@"Device registered successfully.");
                  dispatch_async(dispatch_get_main_queue(), ^{
                  // Update UI if-needed.
                    }) ;
                  } onError:^(NSError *error) {
                      NSLog(@"Error registering your device.");
                      dispatch_async(dispatch_get_main_queue(), ^{
                         // Update UI if-needed.
                      }) ;
                  }];
    }
    

Next, register your mobile app with the associated backend, and enable notifications.

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.
Set Up a Device Handshake for Windows
This section assumes you have already registered your mobile app with WNS as described in the Windows: WNS Credentials chapter.

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 backend, and enable notifications. For detailed instructions, see the Backends chapter.

After you’ve registered your app, it can receive notifications from a range of sources.

Send 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 UI

The service provides a notifications testing UI that allows you to send scheduled notifications to a defined set of recipients.
  1. Click icon to open the side menu to open the side menu and select Development > Backends.
  2. On the Backends page, select the backend that includes your mobile app and click Open.
  3. Click Notifications.
  4. On the Notifications page, click the Send icon.
  5. If your device isn’t registered yet, you can access the Device Registry by clicking Manage Devices.
    To register a device for SMS through the UI, you must have consent management disabled in the associated notifications profile as described in Create a Notifications Profile. If you register a device for SMS through the UI and it fails, it’s probably a problem with your Syniverse Developer Community setup. Make sure you completed all the steps described in Syniverse: SMS Credentials.
  6. Enter the notification message you want to send in plain text or a JSON payload. If you enter JSON, it must conform to the notification provider’s requirements. If it is not valid JSON, it will be sent as a plain text message.
  7. Choose when to send the message.
    • To send the notification immediately, leave the default Now.
    • To schedule the notification for a later date and time, choose Later and select the date and time for the notification to be sent.
  8. Choose who to send the message to.
    • To send the notification to everyone in the mobile backend, leave the default All notifications-enabled mobile apps that use this backend. A single backend may contain more than one version of a mobile application, with implementations for different devices and networks. This option sends to all notification-enabled clients, regardless of the network or device.
    • To define a filter by user name, platform type, device ID, Facebook ID, or any combination, choose Filtered set of recipients. Under Match all of the following, select the filter type from the dropdown list:
      • Device ID: Send a notification to a single device ID or to multiple device IDs at the same time. The device ID is a unique number assigned to a mobile device during the device handshake. For SMS, the device ID is a phone number. In general, sending a notification to a device ID is useful for testing your application but not practical in bulk.

      • Platform: Send to all recipients running on iOS, Android, Windows or Web.

      • Provider: Send to all recipients receiving APNS, FCM, WNS or SMS notifications.

      • User: Send a notification to a single user or to a list of users.

      • Facebook Unique ID: Send a notification to a Facebook user, by ID.

      If the list of recipients gets too long, click the + button to add another filter and continue your entries there. Filters can be mixed and matched for additional selectivity.
  9. Click Send.
Once you click Send, you can monitor the status of your notifications in the History pane.
Cancel a Scheduled Notification from the UI
The only notifications that can be cancelled are those that are scheduled for a future time.
To cancel a scheduled notification, go to the Scheduled tab in the History pane and click the X in the corner of the entry you want to remove. You will be prompted to confirm the cancellation.

Send Notifications Using the Notifications API

You can send notifications to mobile devices from your apps using the Notifications API. Notifications have a maximum limit of 1,000 devices per call.

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 the Notifications API in the Calling APIs from Custom Code in the chapter.

To register a device ID for notifications, you can use the UI or the Notifications Device Registration API.

The /mobile/system/notifications/notifications endpoint allows you to send notifications, cancel scheduled notifications, and check the status of sent notifications.

When you send a notification, you can specify any combination of the following for the payload:
  • {"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 and custom. For details, see Sending a Notification Using a Unified Payload.

  • {"message":""} A plain-text message string. For details, see Sending a Text Message Notification .

The unified payload is used if it exists, then the template, then the message, in that order.

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 by firstname: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@example.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, 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"]}'
To schedule a notification for a future date and time, add the 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 API Reference for Oracle Mobile Cloud.

REST
Register 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.

The Notifications Device Registration API includes the following endpoints:
  • POST /mobile/platform/devices/register

  • POST /mobile/platform/devices/deregister

When you register a device, include these parameters:
  • 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 the notificationToken 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 the user parameter isn’t included, the device ID is associated with the user who is logged in during the registration call. To specify a different user name, the logged in user must be a team member with either the Administrator or Developer 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.

This example registers a device with the device ID 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
If the REST operation to register the device is successful, you can expect to get a response something like this:
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
The response includes a JSON payload that contains the device ID for the registered device.
{
  "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"
}
Send 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).

Send a Notification Using a Unified Payload
A unified payload allows you to specify a different payload for each supported notification provider using Notifications REST API. One or more of the following can be defined under the services property:
  • The apns payload must conform to APNS requirements.

  • The fcm payload can contain arbitrary JSON properties.

  • The wns payload property must contain a well-formed WNS payload.

  • The syniverse payload property should contain the string to send as a SMS message.

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.

Notification object:
{"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"
        }
      }
    }
  }
}
Send a Notification Using a Payload Template
When you use a payload template with the Notifications REST API, the content you enter is used to create a driver-specific payload for each supported notification provider. The default payload template includes the following optional parameters.
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 body is specified, the content is used as the value for the alert property in the APNS and FCM payloads.

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.
  • For APNS, the file must be in the app bundle.

  • For WNS, the file must be in the app package (the "ms-appx:///" prefix is added automatically).

  • For FCM, the file can be anywhere.

string "alert.wav"
custom Any required custom data. object
{
  "acme1": "value1",
  "acme2": ["value2", "value3"]
}

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.

This specifies the default template:
{
 "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 driver payload:
"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\"]" } 
}
Cancel Scheduled Notifications
To cancel a scheduled notification, send DELETE to /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
iOS
Register 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.

The Notifications Device Registration API includes the following endpoints:
  • POST /mobile/platform/devices/register

  • POST /mobile/platform/devices/deregister

When you register a device, include these parameters:
  • 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 the notificationToken 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 the user parameter isn’t included, the device ID is associated with the user who is logged in during the registration call.

    To specify a different user name, the logged in user must be a team member with either the Administrator or Developer 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.

This code shows how to register an iOS device for push notifications:

-(void) registerForMCSNotifications:(id) sender {

     // Get notifications object from your mobile backend object.

    OMCNotifications* notifications = [mbe notifications];

    

   // Call register api and pass the iOS device token data.

    [notifications registerForNotifications:[self getDeviceTokenData]

            onSuccess:^(NSHTTPURLResponse *response) {

            NSLog(@"Device registered successfully.");

            dispatch_async(dispatch_get_main_queue(), ^{

  // Update UI if needed.

             }) ;

             } onError:^(NSError *error) {

               NSLog(@"Error registering your device.");

               dispatch_async(dispatch_get_main_queue(), ^{

//Update UI if needed.

              }) ;

         }];

}

Deregister a Device

// Call register api and pass your iOS device's device token data.

    [notifications deregisterForNotifications:[self getDeviceTokenData]

    onSuccess:^(NSHTTPURLResponse *response) {

     	NSLog(@"Device deregistered successfully.");

     	dispatch_async(dispatch_get_main_queue(), ^{

// Update UI if-needed.

        }) ;

           } onError:^(NSError *error) {

            NSLog(@"Error deregistering your device.");

          dispatch_async(dispatch_get_main_queue(), ^{

       // Update UI if-needed.

      });

  }];
Cordova/JavaScript/TypeScript
Register 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.

The Notifications Device Registration API includes the following endpoints:
  • POST /mobile/platform/devices/register

  • POST /mobile/platform/devices/deregister

When you register a device, include these parameters:
  • 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 the notificationToken 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 the user parameter isn’t included, the device ID is associated with the user who is logged in during the registration call. To specify a different user name, the logged in user must be a team member with either the Administrator or Developer 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.

This code shows how to register a device for push notifications using Cordova/JavaScript/TypeScript:

...
document.addEventListener("deviceready", handleDeviceReady, false);
...
function handleDeviceReady(){
  MCSNotificationsCordovaPlugin.onTokenRefresh(handleTokenRefresh, handleError);
}
...
function handleTokenRefresh(token){
    console.log('NotificationsService Token refreshed', token);
    mcs.mobileBackend.notifications.registerForNotifications(token, packageName, appVersion, 'FCM')
        .then(handleRegisterForNotifications)
        .catch(handleError);
}
 
function handleRegisterForNotifications(response){
    console.log('NotificationsService, device registered for notifications');
}
function handleError(error){
    console.error('NotificationsService Error', error);
}

Deregister a Device

this.mcs.mobileBackend.notifications
 .deregisterForNotifications(token, packageName, appVersion, 'FCM')
 .then(deregisterSuccess)
 .catch(deregisterError);

function deregisterSuccess(response)
{ console.log(response); } 
function deregisterError(response)
{ console.error(response); } 

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.

  1. 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.

  2. The notification is addressed to the associated device IDs and distributed to the appropriate push networks for delivery.

  3. 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

    • 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, which you can read about in Send Notifications to and from Your App.

Troubleshoot 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, the wrong API key or Project Number/Sender ID means the user might have disabled notifications on their device.

The service will automatically unregister the device if a notification is sent to it and the notification provider reports the device ID as being bad. This can happen in a few ways:
  • 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 the service and the notifications provider to refresh it.

  • The user deleted the app from their device

  • The API key or certificate in the service 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.

Check 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. In most cases, there is a configuration error that needs to be fixed.

  • 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 logs to see if more information about a notification or batch of notifications is available. Click icon to open the side menu to open the side menu and select Administration > Logs. For details on the diagnostics tools available, see the Diagnostics chapter.

Check Notification Status with the Notifications REST API

You can use the Notifications API to check the status of notifications.
Send 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.)
The example below checks for scheduled notifications.
curl -i
-X GET 
-u team.user@example.com:Password
-H "Oracle-Mobile-Backend-ID: ABCD9278-091f-41aa-9cb2-184bd0586fce"
http://fif.cloud.oracle.com/mobile/system/notifications/notifications/?status=Scheduled
If the query is successful, the response will be JSON listing the first 1000 notifications found. You can specify a range using limit and offset parameters, for example, 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"
   }
  ]
}