Use Google Cloud Messaging for Push Notifications with NativeScript

NativeScript provides a nice plugin to work with push notifications (https://github.com/NativeScript/push-plugin). They even have a sample app that utilizes Telerik’s own backend platform for the push service. So I wanted to see how easy it was to use the plugin with a different push service. I chose to test this out with Google Cloud Messaging (GCM). It turned out to be pretty simple.

This guide has been tested against Android only, but from the documentation there shouldn’t be too much to change to get it working with iOS.

Go ahead and create a brand new NativeScript project via the CLI, navigate into the project, add the push plugin, and add the android platform:

tns create PushItRealGood
cd PushItRealGood
tns plugin add nativescript-push-notifications
tns platform add android

Okay, now we have a simple NativeScript app with our plugin and the android platform added. Now open up your IDE and lets add some code. We are going to be working directly with the main-page.xml and main-page.js files in the root of the app folder.

app/main-page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
  <StackLayout>
    <Label text="Tap the button to trigger the register function." textWrap="true" class=""/>
    <Button text="REGISTER" tap="registerTap" />    
    <label text="Your device id/token:" textWrap="true" />
    <TextView text="{{ registrationId }}" class="title" textWrap="true"/>
    <Label text="{{ message }}" class="message" textWrap="true" />
  </StackLayout>
</Page>

The important elements here are:

  • Button to execute the pushPlugin.register() method.
  • TextView that will render our registration Id/token.

app/main-page.js

var Observable = require("data/observable");
var pushPlugin = require('nativescript-push-notifications');

var viewModel = new Observable.Observable({
    registrationId: ""
});

function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = viewModel;
}
exports.pageLoaded = pageLoaded;

function registerTap (args) {

  var settings = {
		// Android settings 
		senderID: '<ENTER_YOUR_PROJECT_NUMBER>', // Android: Required setting with the sender/project number 
		notificationCallbackAndroid: function(message) { // Android: Callback to invoke when a new push is received. 
        	console.log(JSON.stringify(message));
            alert(JSON.stringify(message));            
        },
 
		// iOS settings 
        badge: true, // Enable setting badge through Push Notification 
        sound: true, // Enable playing a sound 
        alert: true, // Enable creating a alert 
 
        // Callback to invoke, when a push is received on iOS 
        notificationCallbackIOS: function(message) {
        	alert(JSON.stringify(message));
        }
	};
        
	pushPlugin.register(settings,
		// Success callback 
		function(token) {
              // if we're on android device we have the onMessageReceived function to subscribe 
			// for push notifications 
			if(pushPlugin.onMessageReceived) {
				pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
			}
 
			alert('Device registered successfully : ' + token);
            viewModel.set("regId", token);
		},
		// Error Callback 
		function(error){
            console.log(error);
			alert(error.message);
		}
	);
}
exports.registerTap = registerTap;

A few notes about the javascript code:

  • We are requiring the ‘Observable’ module for our viewmodel and the pushPlugin module for well the push plugin 🙂
  • The ‘viewModel’ property ‘registrationId’ is going to render our registrationId (token) returned from the .register() method.

Almost there…

Okay so now we have an app with almost all of the changes necessary, the rest is making sure we have an app/project for with Google Cloud Messaging API enabled.

Open up the Google Developer Console: https://console.developers.google.com/project to view your projects. If you don’t have a project it takes about 10 seconds to create one.
Click the ‘Create Project’ button and enter your project name. createProjectprojectNumber.

Once the project is created you’ll be taken to the main page for your project. Then you’ll find your ‘Project number‘, this number is what you’ll need to put into our main-page.js file in the settings object for the senderId property at the beginning of our registerTap() function.

You also need an API key for your project, but it can wait if until we start making our requests to GCM. To get this, enable the Google Cloud Messaging for Android API and then set your credentials and you’ll find your API key.apikey

Once you have modified the senderId value to your Google project number, you are ready to build and run the app.

 

tns run android

Once your app runs, click the REGISTER button and your Registration Id should render in the TextView. In a production app, you’d want to store this registration Id/token on your database with some association of who the user is, what platform the device is and any other information you might need. To keep this example simple and more of a proof of concept we are going to switch over to POSTMAN to make our HTTP POST to the GCM service to get our push notifications. If you don’t have PostMan, you can use other tools that allow testing of HTTP requests.

The GCM docs are very thorough and provide a ton of information but what we need is available here at https://developers.google.com/cloud-messaging/downstream.

Open up POSTMAN and lets get some notifications.

Set the POST url to:

https://gcm-http.googleapis.com/gcm/send

Open the ‘Headers’ tab in POSTMAN and set the required headers: ‘Authorization’ and ‘Content-Type’.
The value for the ‘Authorization’ header is going to be your API KEY from your Google project. The value will look like the following:
key=ALxkakd12i39ksdlcjd…. For the ‘Content-Type’ header I’m using application/json but you could use Plain Text if you wanted, according to the GCM docs.

Final Steps

Open the ‘Body’ tab in POSTMAN, click the ‘raw’ radio button and create your message to send to the GCM service.

{
    "to": "fQFG5jd3sc1WrM:APckd25bFn3mgva.....",
             
    "notification" : {
        "title" : "NativeScript",
        "body" : "GCM Push Baby!!!",
        "icon" : "icon",
        "color" : "#FF4081"
    }
     
}

The important part to our JSON data is the to property, the value of this is our Registration Id from our app when we tapped the button. Once you finish adding your device’s registration Id as the “to” property’s value, click SEND and you should receive your notification!!! If you do not, GCM has some good documentation on the various errors you might be receiving.

YOU ARE DONE!

I know that seemed kind of lengthy but this is as simple as it gets in testing push notifications. There are several other options available from GCM and you can implement them if you want but this guides purpose was to keep things simple. If you have any questions or comments I’d love to hear them. Thanks!

24 thoughts on “Use Google Cloud Messaging for Push Notifications with NativeScript

  1. How to make app always running on background? For now I cannot receive push notification when app is exist. So I have to open app then I can receive push notification.

    Like

    1. That shouldn’t be the case Frank. When I tested this it worked when the app was not open. If you have any issues with the plugin, file an issue on the NativeScript push plugin repo. Maybe some things have changed since I wrote this. Thanks for reading 🙂

      Like

  2. Push notification will not received after few mins via postman. But it is worked at the first few mins after tns run android. Have tou met same issus?

    Like

  3. If “onMessageReceived” function is there notification is not coming in notification bar.If I remove this then only notification is showing in notification bar.Is it weird or expected behaviour?

    Like

    1. @Karteek – join the NativeScript slack channel. I’d be glad to chat about the issues you have there, it’s easier than blog comments 🙂 there are numerous NativeScript experts on the slack community who can help, some much more knowledgeable than I am. As for this behavior I’m not sure I understand the entire context of your question. Possibly a language gap but I’ll try to help you if I can. Thanks for reading.

      Like

  4. Hi Bradmartin,

    When i send data from POSTman. It always return NULL. Im not sure which part i had done wrong

    {
    “to”:”ebI5MjiKWOY:APA91bFS3BQ9gyz3mI3uQPVDZ3IGkKk2Pe_cxXpCBmeSgHZT6TJg1QuASvFNtm3yqY3mK6EZBEhqGfhWmgK_y3VMjv1k5B_5H1cvePNIaHos4lHuUlFzxEjdgnB54FuI5cHj_KMK0wc4″,
    “notification” : {
    “title” : “NativeScript 2”,
    “body” : “GCM Push Baby!!!”,
    “icon” : “icon”,
    “color” : “#FF4081”
    },
    “data”: {
    “msg”: “5×1”
    }
    }

    Like

    1. Hi Robert, it is similar I believe. It might even be easier with the firebase plugin for NativeScript. Eddy Verbruggen has done awesome work with it and last I checked the FCM stuff was there. Also if you have any questions the NativeScript slack community is top notch and full of great devs. You can also ping me in there 🙂 the slack link is on the homepage of NativeScript.org site if you do join say hi so I know you made it.

      Like

  5. Hello, I’ve tried everything in order to get working the “onMessageReceived” callback, but nobody on the nativescript-push-plugin repo can suggest how to do… I don’t think that this plugin is able to working as expected, too issues, but I’ve no alternatives for my project. I don’t know really what to do.

    The others callbacks works like a charm, but it isn’t possible to receive notifications from that callback.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s