Example: Sending push notifications Register devices for receiving notifications

Make your backend server send push notifications through this UnifiedPush Server.

Use the code snippet bellow to register your device and allow it to receiving notifications through this UnifiedPush Server.

(function() { var endpoint, endpointRequest, SPClient, UPClient; // config params for UnifiedPush server var variantId = "{{ variant.variantID }}"; var variantSecret = "{{ variant.secret }}"; var unifiedPushUrl = "{{ currentLocation }}"; // If your SimplePush Server is running on Openshift, the URL is {{ simplePushUrl() }} // If your SimplePush Server is using Mozilla's network, the URL will be wss://push.services.mozilla.com // or do you run a custom server? var simplePushUrl = "[URL of the SimplePush Server you are using]"; // create the 'UnifiedPush' client object: UPClient = AeroGear.UnifiedPushClient(variantId, variantSecret, unifiedPushUrl); // onConnect callback function called when SimplePush // successfully establishes connection to the server function spConnect() { // use 'PushManager' to request a new PushServer URL endpoint for 'Mail' notifications: endpointRequest = navigator.push.register(); // the DOMRequest returns 'successfully': endpointRequest.onsuccess = function( event ) { // extract the endpoint object from the event: endpoint = event.target.result; // if it is the first registration, need to register // the 'pushEndpoint' with the UnifiedPush server. if ( endpoint ) { // assemble the metadata for registration with the UnifiedPush server var metadata = { deviceToken: endpoint }; var settings = { success: function() { //success handler }, error: function() { //error handler } }; settings.metadata = metadata; // register with the server UPClient.registerWithPushServer(settings); } else { console.log("'Endpoint' was already registered!"); } }; // set the notification handler: navigator.setMessageHandler( "push", function( message ) { if ( message.pushEndpoint === endpoint ) { // let's react on the endpoint } }); } // onClose callback function: function spClose() { // handle onclose - e.g. allow reconnect } SPClient = AeroGear.SimplePushClient({ simplePushServerURL: simplePushUrl, onConnect: spConnect, onClose: spClose }); })();
chrome.pushMessaging.getChannelId( true, function(channelId) { /* Set our Variant ID and Secret and the location of the UnifiedPush Server */ var variantId = "{{ variant.variantID }}", variantSecret = "{{ variant.secret }}", pushServerURL = "{{ currentLocation }}"; // Once we have the channelID we can then register with the UnifiedPush Server using // the AeroGear.js library var client = AeroGear.UnifiedPushClient( variantId, variantSecret, pushServerURL ),settings = {}; // The channelId will be the "device token" settings.metadata = { deviceToken: channelId.channelId }; // Register with the UnifiedPush Server client.registerWithPushServer( settings ); });
package com.push.pushapplication; import java.net.URI; import java.net.URISyntaxException; import org.jboss.aerogear.android.unifiedpush.PushConfig; import org.jboss.aerogear.android.unifiedpush.PushRegistrar; import org.jboss.aerogear.android.unifiedpush.Registrations; import android.app.Application; public class PushApplication extends Application { private final String VARIANT_ID = "{{ variant.variantID }}"; private final String SECRET = "{{ variant.secret }}"; private final String GCM_SENDER_ID = "{{ variant.projectNumber }}"; private final String UNIFIED_PUSH_URL = "{{ currentLocation }}"; private PushRegistrar registration; @Override public void onCreate() { super.onCreate(); Registrations registrations = new Registrations(); try { PushConfig config = new PushConfig(new URI(UNIFIED_PUSH_URL), GCM_SENDER_ID); config.setVariantID(VARIANT_ID); config.setSecret(SECRET); config.setAlias(MY_ALIAS); registration = registrations.push("unifiedpush", config); registration.register(getApplicationContext(), new Callback() { private static final long serialVersionUID = 1L; @Override public void onSuccess(Void ignore) { Toast.makeText(MainActivity.this, "Registration Succeeded!", Toast.LENGTH_LONG).show(); } @Override public void onFailure(Exception exception) { Log.e("MainActivity", exception.getMessage(), exception); } }); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); var pushConfig = { pushServerURL: "{{ currentLocation }}", {{ cordovaVariantType(variant) }}: { {{ projectNumber(variant) }} variantID: "{{ variant.variantID }}", variantSecret: "{{ variant.secret }}" } }; push.register(app.onNotification, successHandler, errorHandler, pushConfig); function successHandler() { console.log('success') } function errorHandler(message) { console.log('error ' + message); } }, onNotification: function(event) { alert(event.alert); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } }; app.initialize();

It's also possible to use an external config file named push-config.json and placed in the root of your www folder :



// ../www/push-config.json
{
  "pushServerURL": "{{ currentLocation }}",
  {{ cordovaVariantType(variant) }} : {
    {{ projectNumberJson(variant) }}
    "variantID": "{{ variant.variantID }}",
    "variantSecret": "{{ variant.secret }}"
  }
}


And then :
var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); push.register(app.onNotification, successHandler, errorHandler); function successHandler() { console.log('success') } function errorHandler(message) { console.log('error ' + message); } }, onNotification: function(event) { alert(event.alert); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } }; app.initialize();
JavaSender defaultJavaSender = new SenderClient.Builder("{{ currentLocation }}").build(); UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .pushApplicationId("{{ applicationId }}") .masterSecret("{{ application.masterSecret }}") .alert("Hello from Java Sender API!") .build(); defaultJavaSender.send(unifiedMessage, new MessageResponseCallback() { @Override public void onComplete(int statusCode) { //do cool stuff } @Override public void onError(Throwable throwable) { //bring out the bad news } });
using AeroGear.Push; protected async override void OnLaunched(LaunchActivatedEventArgs e) { PushConfig pushConfig = new PushConfig() { UnifiedPushUri = new Uri("{{ currentLocation }}"), VariantId = "{{ variant.variantID }}", VariantSecret = "{{ variant.secret }}" }; Registration registration = new WnsRegistration(); registration.PushReceivedEvent += HandleNotification; await registration.Register(pushConfig); ... } void HandleNotification(object sender, PushReceivedEvent e) { Debug.WriteLine("notification received {0}", e.Args.message); }
using AeroGear.Push; protected async override void OnLaunched(LaunchActivatedEventArgs e) { PushConfig pushConfig = new PushConfig() { UnifiedPushUri = new Uri("{{ currentLocation }}"), VariantId = "{{ variant.variantID }}", VariantSecret = "{{ variant.secret }}" }; Registration registration = new MpnsRegistration(); registration.PushReceivedEvent += HandleNotification; await registration.Register(pushConfig); ... } void HandleNotification(object sender, PushReceivedEvent e) { Debug.WriteLine("notification received {0}", e.Args.message); }