Using the Push Notifications Mobile Service

The Push Notifications service allows you to send native push notifications to different mobile operating systems.

  • Code once and push notifications to iOS and Android.

  • Push notifications to defined groups.

  • Push notifications to either iOS only or Android only.

  • Push notifications to different variants of a mobile app.

  • Push notifications from different back-end apps to the same mobile app.

Currently the service supports:

The Push Notifications service offers a unified Notification Service API to the above mentioned Push Network Services. It can be seen as a broker that distributes push messages to different 3rd party Push Networks.

  • The payload of the push notification is delivered to 3rd party Push Network providers, Google or Apple. AeroGear recommends that users do not send any sensitive personal or confidential information (for example, a social security number, financial account or transactional information) as part of any Push Notification. Users of push notifications should not have an expectation of secure transmission.

  • For analytic purposes, the service stores the content of the alert key sent to the UnifiedPush Server. The content of the alert key belongs to the metadata, which is deleted after 30 days, using a nightly job within the UnifiedPush Server.

  • You are only able to send push notifications to a real device, sending push notifications to an emulator fails.

  • Push is a signalling mechanism and is not suitable to be used as a data carrying system, for example, a chat application.

Prerequisites
  • You understand Push Notifications.

  • You have logged into the OpenShift console and the Mobile Developer Console.

Push Notifications Terminology

This section describes terminology that is associated with Push Notifications.

Push Application

A logical construct that represents an Mobile App, for example, Mobile HR.

Push Notification Message

A simple message to be sent to a Push Application.

Sender Endpoint API

A RESTful API that receives Push Notification Message requests for a PushApplication or some of its different Variants. The Server translates this request into the platform specific details and delivers the payload to the 3rd party cloud providers, which eventually might deliver the message to the physical device.

Variant

A variant of the Push Application, representing a specific mobile platform, like iOS or Android, or even more fine-grained differentiation like iPad or iPhone. There can be multiple variants for a single Push Application (for example, Mobile HR Android, Mobile HR iPad, Mobile HR iOS free or _Mobile HR iOS premium). Each supported variant type contains some platform specific properties, such as a Google API key (Android) or passphrase and certificate (Apple).

APNs

Apple Push Notification service.

Installation

Represents an actual device, registered with the UnifiedPush Server. User1 running HR Android app, while User2 runs HR iPhone premium on his phone.

Administrative User Interface

(AUI) The Unified Push Admin UI Web UI that allows you manage Push Applications and Variants, view statistics and send Push Notifications to devices.

Setting Up the Push Notifications Mobile Service

Obtaining Firebase Cloud Messaging Credentials

This procedure describes how to obtain Firebase Cloud Messaging Credentials.

Prerequisites

Before the Android application is able to receive the notifications, you must set up access to Firebase Cloud Messaging. The following credentials are necessary to set up Firebase Cloud Messaging for your app:

  • Server key

  • Sender ID

  • google-services.json file containing the credentials required to connect your app to Firebase and Google services.

Procedure
  1. From the Project Settings screen, switch to the Cloud Messaging tab, where you can find the Server key and Sender ID (known in GCM as Project Number). There is also a Legacy server key but it should not be used for new projects.

  2. Download the google-services.json file as described in the Google Documentation.

Obtaining Apple Push Notification Service Credentials

This procedure describes how to enable Push Notifications for your iOS application and get the credentials required for push from Apple.

Procedure
  1. Follow the official Apple guide to enable push notifications for your Xcode project.

  2. Follow the official Apple guide to generate an APNs client TLS certificate and export the client TLS identity from your Mac.

    Make sure to protect the p12 file with a password.

    The exported p12 file with the password will be used later when binding your Mobile App to the Push Notifications.

Provisioning the Push Notifications Service

This section describes how to set up the Push Notifications Mobile Service.

Procedure
  1. Log into the OpenShift console.

  2. Create a new project or choose an existing project.

  3. Click Add to Project and choose Browse Catalog from the options.

    You can filter the catalog items to only show mobile specific items by clicking the Mobile tab.

  4. Click Services and choose the service.

    catalog mobile services
  5. Follow the wizard for provisioning that service.

    If prompted to Create a Binding, choose Do not bind at this time

Once the wizard steps are completed, navigate to the Project Overview in OpenShift to see the newly provisioned service. Provisioning a service may take some time.

Binding a Mobile App with the Push Notifications Service

To use mobile services, you must represent your mobile app in Mobile Developer Console, and that app must be associated with the mobile service. This association is called binding and it is necessary for your mobile app to use that service.

Prerequisites
  • You have created a Mobile App.

  • Android

  • iOS

  • Google account

  • Access to the Firebase console. Refer to Firebase Docs.

Procedure

To bind a Mobile App with a mobile service:

  1. Log in to the Mobile Developer Console.

  2. Click on the Mobile App on the Overview screen.

  3. Navigate to Mobile Services tab.

    mobile clients services all unbound
    It is possible to bind a Mobile App with a mobile service in the OpenShift console, however such bindings are not valid for the purposes of this procedure.
  4. Press Bind to App in the Push Notifications.

  5. Fill out the binding parameters required by the Push Notifications Service.

    When you bind a mobile client to the Push Notifications service, a variant is created to store the credentials required to communicate with a push network. Those credentials need to be provided in the binding dialog.

    Choose a Mobile Client Type and fill out the required fields:

    • Android

    • iOS

    • Select Android from in the Mobile Client Type list.

    • Enter a Server Key and a Sender ID. Both are present in the Firebase console.

    mobile clients services push parameters android
    • Select iOS from the Mobile Client Type list.

    • Obtain an APNs client TLS certificate. Refer to official Apple guide.

    • Encode the certificate using base64 and paste the encoded certificate into the field labeled iOS .p12 file.

      If you are using macOS:

      cat <path/to/your/.p12> | base64

      If you are using Linux and a version of base64 that wraps lines, disable line wrapping as follows:

      cat <path/to/your/.p12> | base64 --wrap=0
    mobile clients services push parameters ios

    After clicking Create your variant will be created in UPS and you should see a new binding for your mobile client. A variant is used for the storage of the credentials provided in the Binding procedure.

Configuring your client app

Downloading the Configuration File

The mobile-services.json file provides the information for your mobile app to communicate with services. After you change any configuration in the Mobile Developer Console, it is important to update that file in your IDE.

Prerequisites
  • The configuration of your Mobile App in Mobile Developer Console is up-to-date.

  • You have set up your mobile app development environment.

Procedure
  1. Open your Mobile App in Mobile Developer Console.

  2. Copy the mobile-services.json configuration to your clipboard.

  3. Save the contents of the clipboard to a new file called mobile-services.json.

    The mobile-services.json file is the link between your provisioned services on OpenShift and the mobile app you are developing. This file provides all required configuration to initialise the various SDKs and get them hooked up/connected to the back-end services.
  4. Move mobile-services.json to the following location in your application project:

    • Android

    • iOS

    • Cordova

    • Xamarin

    app/src/main/assets/mobile-services.json

    <app directory>/mobile-services.json NOTE: Ensure that mobile-services.json is a member of the project in the Xcode Project Navigator.

    src/mobile-services.json

    To run the Cordova app on the Android device you also need to download the google-services.json from Firebase and put it on the root folder of your project.

    Resources/mobile-services.json

Setting up the Push Notifications Service SDK

This section helps you to set up the Push Notifications service SDK in your App. It describes how to set up and initialize the Push Notifications service SDK.

Prerequisites
  • Your local mobile-services.json file is up-to-date.

  • Android

  • iOS

Procedure
  1. Import the libraries

    • Android

    • iOS

    • Cordova

    • Xamarin

    1. Add the push dependency to your application module

      implementation "org.aerogear:aerogear-push:1.0.0"
      implementation "com.google.firebase:firebase-messaging:[version]"
    2. Create a new project in Firebase console

    3. Add The Google Services Gradle Plugin in your root build.gradle file

        buildscript {
            dependencies {
                classpath 'com.google.gms:google-services:[version]'
            }
        }
    4. Apply the plugin in your app build.gradle file

        // ADD THIS AT THE BOTTOM
        apply plugin: 'com.google.gms.google-services'
    1. Add the dependency to your Podfile

      target '[TARGET NAME]' do
          pod 'AGSPush', '[VERSION]'
      end
    2. Update the dependencies

      $ pod install
    3. Import the SDK

      import AGSPush
    1. Install cordova-plugin-aerogear-push:

      $ cordova plugin add @aerogear/cordova-plugin-aerogear-push
    2. Install the Unified Push Server package needed for device registration:

      $ npm install --save @aerogear/push

    This feature is not yet supported in the AeroGear Xamarin SDK

Registering device on Push Notifications Service

To receive native push notifications from a Push Network, for example APNs or FCM, the mobile device is identified with a unique device-token assigned by that Push Network. This device-token is passed, by the operating system, to the mobile application. Refer to the operating system and Push Network documentation for further details.

Every time a user launches a mobile app, that app receives the device-token, from a platform-specific method (or callback). Since the Push Network may assign a new token to a device, AeroGear recommends that the app registers the device-token with the UnifiedPush Server each time.

The required metadata for an Installation:

  • deviceToken: _Identifies the device/user-agent within its Push Network.

  • variantID: The ID of the variant, where the client belongs to

  • variantSecret: Password of the actual variant

The AeroGear UnifiedPush Server is able to store some user-specific metadata as well:

  • deviceType: The device type of the device or the user agent.

  • operatingSystem: The name of the underlying Operating System.

  • osVersion: The version of the used Operating System.

  • alias: Application specific alias to identify users with the system. For instance an email address or a username.

  • categories: Used to apply one or more "tags".

The device-token needs to be registered with the AeroGear UnifiedPush Server, to indicate there is a new Installation for a Variant. This registration is performed by calling an endpoint of the server.

  • Android

  • iOS

  • Cordova

  • Xamarin

  1. Getting an instance of the PushService

    PushService pushService = new PushService.Builder().openshift().build();
  2. Registration request

    pushService.registerDevice()
      .requestOn(new AppExecutors().mainThread())
      .respondWith(new Responder<Boolean>() {
        @Override
        public void onResult(Boolean value) { // Yay }
    
        @Override
        public void onException(Exception exception) { // Oops! }
    });
func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var config = UnifiedPushConfig()
    AgsPush.instance.register(
        deviceToken,
        config,
        success: {
           print("Successfully registered to Unified Push Server")
        },
        failure: { (error: Error!) in
           print("Failure to register for on Unified Push Server: \(error)")
        }
    )
}
import { PushRegistration } from "@aerogear/push";

new PushRegistration(app.config).register().then(() => {
    // Registration with UPS successful, you can now send push notifications from the UPS UI
}).catch(err => {
    // Error on device registration
});
Optionally, you can pass the parameters below to the register method
{
  alias: 'some-alias',
  categories: ['one', 'or', 'more', 'categories'],
  timeout: 5000 // in milliseconds
}

This feature is not yet supported in the AeroGear Xamarin SDK

Sending a Push Notification using the Unified Push Admin UI

The Unified Push Admin UI allows you to send Push Notifications.

Prerequisites
  • Make sure the Push Notifications service is provisioned.

  • Select a route in OpenShift.

  • Login with your OpenShift credentials.

On first login you need to provide the OpenShift OAuth service permissions to read your user account.
  • Admin UI

  • Java API

  • Node.js API

  • REST

  1. Open the Unified Push Admin UI in a browser.

  2. Select the target application from the home page and click Send Notification To This App.

    Send a Push
  3. When the Send Push dialog displays, enter text in the Message form.

    Enter the payload
  4. Click Send Push Notification to send the message to the target application.

  1. Add unifiedpush-java-client as a dependency to your project.

    <dependency>
      <groupId>org.jboss.aerogear</groupId>
      <artifactId>unifiedpush-java-client</artifactId>
      <version>[version]</version>
    </dependency>
  2. Send the message to the target application.

    final PushSender sender = DefaultPushSender
            .withRootServerURL("<pushServerURL e.g http(s)//host:port/context>")
            .pushApplicationId("<pushApplicationId e.g. 1234456-234320>")
            .masterSecret("<masterSecret e.g. 1234456-234320>")
            .build();
    
    final UnifiedMessage unifiedMessage = UnifiedMessage
            .withMessage()
            .alert("Hello from Java Sender API!")
            .build();
    
    sender.send(unifiedMessage, () -> {
        //do cool stuff
    });
  1. Add unifiedpush-node-sender as a dependency to your project.

    npm i unifiedpush-node-sender
  2. Send the message to the target application.

    const agSender = require('unifiedpush-node-sender');
    
    const settings = {
      url: "<pushServerURL e.g http(s)//host:port/context>",
      applicationId: "<pushApplicationId e.g. 1234456-234320>",
      masterSecret: "<masterSecret e.g. 1234456-234320>"
    
    };
    
    const message = {
      alert: "Hello from the Node.js Sender API!"
    };
    
    const options = {
      config: {
        ttl: 3600
      }
    };
    
    agSender(settings).then((client) => {
      client.sender.send(message, options).then((response) => {
        console.log('success', response);
      }).catch((error) => {
        console.log('error', error);
      })
    });
  1. Send the message to the target application.

    curl -u "<pushApplicationId>:<masterSecret>"  \
       -v -H "Accept: application/json" -H "Content-type: application/json"  \
       -X POST  -d \
      '{
         "message": {
          "alert": "Hello from the curl HTTP Sender!",
          "sound": "default"
         }
       }'  \
       <pushServerURL>/rest/sender
The 3rd party Push Network is responsible for delivering the Push Notification to the target application.

Handling Incoming Push Notifications

This section describes how to handle incoming push notifications in your foregrounded application.

Push notifications that arrive when the application is in the background are always handled by the OS.
  • Android

  • iOS

  • Cordova

  • Xamarin

Add to your project an implementation of MessageHandler:

public class MyMessageHandler implements MessageHandler {

    @Override
    public void onMessage(Context context, Map<String, String> message) {
        // Handle incoming message
    }

}

Add it to your application’s manifest.

<meta-data
    android:name="DEFAULT_MESSAGE_HANDLER_KEY"
    android:value=".MyMessageHandler" />

The AeroGear SDK for iOS does not provide a way to handle incoming messages. Instead, follow the Apple’s official documentation about notifications.

Add the following code to your app:

import { PushRegistration } from "@aerogear/push";

PushRegistration.onMessageReceived((notification: any) => {
  console.log('Received a push notification', notification);
});

This feature is not yet supported in the AeroGear Xamarin SDK