16 Notifications

Oracle Mobile Cloud Service (MCS) 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)

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.

  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

    • 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

To set up your Android app for notifications, follow the steps below:
  1. First, get credentials from the notification provider to establish your mobile app as a known item on the network. See Android: Google API Key.

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

  3. 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
Configuring an Android mobile app for notifications requires Firebase Cloud Messaging (FCM), formerly Google Cloud Messaging (GCM). GCM is being phased out, so you should configure new apps with FCM. For information on migrating existing apps, see Migrate a GCM Client App for Android to Firebase Cloud Messaging on Google Developers.
For details on setting up your Android mobile application, see Set Up a Firebase Cloud Messaging Client App on Android on Google’s developer site. This page includes detailed instructions and a link to generate the required configuration file for your project, as well as information on using the Instance ID API to create and update registration tokens.

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

For GCM notifications, in the Android app’s AndroidManifest.xml file, within the <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.

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
    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();
  }
}
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.
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 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.

In your app’s 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> 
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"/>
<permission android:protectionLevel="signature"
            android:name=YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<uses-permission android:name="YOUR.PACKAGE.NAME.permission.C2D_MESSAGE"/>
<application>
To establish communication and register for notifications, here’s what the device handshake might look like in an Android app, using the SDK:
...
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.

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

To set up your iOS app for notifications, follow the steps below:
  1. First, get credentials from the notification provider to establish your mobile app as a known item on the network. See iOS: Apple Secure Certificates.

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

  3. 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 require additional secure certificates from Apple, in addition to the certificate used to set up your account. This section assumes you have an Apple Developer account. For information on using notifications in iOS, see the Local and Remote Notification Programming Guide on http://developer.apple.com.

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.

  1. If you didn’t enable notifications in your provisioning profile when you created your App ID, go back and enable it now.
  2. Get your certificate(s) from the Apple Developer Center. Use the App ID you set up when you created your app.

    Note:

    Follow Apple’s direction to create a Certificate Signing Request (CSR) file, then export it to a .p12 file to upload it to MCS. Do not password protect the .p12 secure certificate. (Leave the password field blank when you save the .p12 file.)
You need your certificate to register the mobile app for notifications in MCS. It is unique to the mobile app and can’t be used to send notifications to any other app. Once you have configured these extra certificates, you can get a device token from Apple and set up communication with MCS, described in Setting Up a Device Handshake for iOS.
Setting 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 = [[OMCMobileBackendManager sharedManager] mobileBackendForName:
         <Name_of_Mobile_Backend_from_OMC.Plist>].authorization;
       OMCNotifications* omcNOtifications=nil;
       NSError* err = [auth authenticate:<Username> password:<Password>];
       if (!err){
          omcNotifications = [[[OMCMobileBackendManager sharedManager] mobileBackendForName:
             <Name_of_Mobile_Backend_from_OMC.Plist>] notifications];
       }
       return omcNotifications;
    }
    
  3. Register for notifications using the Notifications SDK object. Note that omcNotifications is the object of OMCNotifications.class. .
    [omcNotifications registerForNotifications:dataDeviceToken
    	onSuccess:^(NSHTTPURLResponse *response){
    		dispatch_asynch(dispatch_get_main_queue(),^{
    			//Update UI here
    		});
    	} onError:^(NSError *error){
    	dispatch_async(dispatch_get_main_queue(),^{
    			//Update UI here
    		});
    	}];

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

To set up your Windows app for notifications, follow the steps below:
  1. 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.

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

  3. 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
Configuring a Windows mobile app for notifications requires a unique set of credentials for Windows Push Notification Service (WNS). This section assumes you have a Microsoft Developer account.
The following credentials are required to authenticate with WNS:
  • 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

  1. Go to the Syniverse Developer Community (developer.syniverse.com).

  2. Click Sign Up in the top right corner of the site and enter the requested information.

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

  4. Read and accept the Terms of Service.

  5. Check the Captcha box and answer the challenges to prove you aren’t a robot.

  6. Click Create profile.

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

  1. Log in to the Syniverse Developer Community (developer.syniverse.com).

  2. Click your user name in the top right corner and select Company. Verify that your accounts have a billing address associated with them.

  3. Navigate to Service Offerings > Messaging Offering and click Subscriptions.

  4. Click Subscribe and select “Initial account for [Your username]”

    1. Read and accept the Terms of Service.

    2. Select Confirm.

    3. Verify that your account is listed in Subscriptions.

  5. 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.)

    1. Click your user name in the top right corner and select Company.

    2. On the Company page, click the Whitelist tab.

    3. Click Add phone number and enter your phone number in the ITU-T E.164 format (i.e., +11234567890).

    4. Click Send confirmation code to send a randomly generated number to the phone number in a text message.

    5. Retrieve the confirmation code from the text message and enter it in the Confirmation code field. Click Add to confirm the phone number whitelist.

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

  1. Log in to the Syniverse Developer Community (developer.syniverse.com).

  2. Click Applications.

  3. Click New application.

    In the dialog:

    1. Give your application a name and description and click Save.

    2. Click the gear icon next to your app name and select Edit.

    3. Click SDC Self Service and make sure all the options are selected.

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

    5. Click Save.

  4. Generate the required credentials:

Setting Up a Device Handshake for Windows
This section assumes you have already registered your mobile app with WNS, described in Windows: WNS Credentials.
Here’s what a device handshake might look like in a Windows app, using the SDK:
...

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

MCS provides a notifications testing UI that allows you to send scheduled notifications to a defined set of recipients.
  1. Make sure you’re in the environment where you want to create the notification. Click icon to open the side menu to open the side menu and select Applications > Mobile Backends.
  2. On the Mobile Backends page, select the mobile 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 MCS client profile as described in Client Management. 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 mobile backend. A single mobile 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, GCM, 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. For details, see Troubleshooting Notifications.
Cancelling 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.

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

The /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 the MobileEnvironment_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 the MobileEnvironment_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.

When you send a notification, you can specify any combination of the following for the payload: 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@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"]}'
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 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.

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.

    Note:

    To specify a different user name, the logged in user must be a team member with the MobileEnvironment_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.
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"
}
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
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 gcm or 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.

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.

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"
        }
      }
    }
  }
}
Sending 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\"]" } 
}
Cancelling 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

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.

MCS 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 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 icon to open the side menu 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

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:Welcome1!
-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"
   }
  ]
}