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 = "{{ exampleCtrl.variant.variantID }}"; var variantSecret = "{{ exampleCtrl.variant.secret }}"; var unifiedPushUrl = "{{ exampleCtrl.currentLocation }}"; // If your SimplePush Server is running on Openshift, the URL is {{ exampleCtrl.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 }); })();
package com.push.pushapplication; import org.jboss.aerogear.android.core.Callback; import org.jboss.aerogear.android.unifiedpush.PushRegistrar; import org.jboss.aerogear.android.unifiedpush.RegistrarManager; import org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushConfiguration; import android.app.Application; public class PushApplication extends Application { private final String TAG = PushApplication.class.getName(); private final String VARIANT_ID = "{{ exampleCtrl.variant.variantID }}"; private final String SECRET = "{{ exampleCtrl.variant.secret }}"; private final String GCM_SENDER_ID = "{{ exampleCtrl.variant.projectNumber }}"; private final String UNIFIED_PUSH_URL = "{{ exampleCtrl.currentLocation }}"; @Override public void onCreate() { super.onCreate(); try { RegistrarManager.config("register", AeroGearGCMPushConfiguration.class) .setPushServerURI(new URI(UNIFIED_PUSH_URL)) .setSenderIds(GCM_SENDER_ID) .setVariantID(VARIANT_ID) .setSecret(SECRET) .asRegistrar(); PushRegistrar registrar = RegistrarManager.getRegistrar("register"); registrar.register(getApplicationContext(), new Callback() { @Override public void onSuccess(Void data) { Log.i(TAG, "Registration Succeeded!"); } @Override public void onFailure(Exception e) { Log.e(TAG, exception.getMessage(), exception); } }); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } 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: "{{ exampleCtrl.currentLocation }}", {{ exampleCtrl.cordovaVariantType(exampleCtrl.variant) }}: { {{ exampleCtrl.projectNumber(exampleCtrl.variant) }} variantID: "{{ exampleCtrl.variant.variantID }}", variantSecret: "{{ exampleCtrl.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": "{{ exampleCtrl.currentLocation }}",
  "{{ exampleCtrl.cordovaVariantType(exampleCtrl.variant) }}" : {
    {{ exampleCtrl.projectNumberJson(exampleCtrl.variant) }}
    "variantID": "{{ exampleCtrl.variant.variantID }}",
    "variantSecret": "{{ exampleCtrl.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("{{ exampleCtrl.currentLocation }}").build(); UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .pushApplicationId("{{ exampleCtrl.applicationId }}") .masterSecret("{{ exampleCtrl.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("{{ exampleCtrl.currentLocation }}"), VariantId = "{{ exampleCtrl.variant.variantID }}", VariantSecret = "{{ exampleCtrl.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("{{ exampleCtrl.currentLocation }}"), VariantId = "{{ exampleCtrl.variant.variantID }}", VariantSecret = "{{ exampleCtrl.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); }