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. .
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.
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!
Excellent article, it works prefectly, thank you!
LikeLike
Thanks Anderson, hope it helps you out.
LikeLike
hello, when i click on help i get an error- ‘alert:: undefined’, pls help..
LikeLike
*when i click on register
LikeLike
Same Issue 😦
LikeLike
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.
LikeLike
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 🙂
LikeLike
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?
LikeLike
I had no issues when I wrote this but that’s been a few months now. So things have changed I’m sure
LikeLike
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?
LikeLike
@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.
LikeLike
Hi bradmartin. I was wondering if I could use this plugin to do POST, PUT, DELETE, and GET requests on the background?
LikeLike
Hi John. There is a background http plugin from the NativeScript team that you’ll want for that.
LikeLike
Hey bradmartin. What’s the name of the background http plugin?
LikeLike
Try searching plugins on npm or use a good community site at http://plugins.nativescript.rocks
LikeLike
Ok Thanks 🙂
LikeLike
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”
}
}
LikeLike
I had some problem with handling data in notifications.I can I get that data..Please give me some solution.
LikeLike
Hi Brad,
Since GQM is being moved over to FCM (firebase), would the steps be similar?
LikeLike
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.
LikeLike
Hi ..bradmartin… thak u so much for this example…
LikeLiked by 1 person
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.
LikeLike
Sorry to just now get back to you. There is an updated guide using FCM (firebase cloud messaging) since google is moving away from GCM. It seems to be working from this tutorial from Nic Raboy http://developer.telerik.com/products/nativescript/use-firebase-cloud-messaging-nativescript-app/ – hope that helps 🙂
LikeLike
Hey, does it work with php script instead of postman? I posted a question here: https://github.com/NativeScript/push-plugin/issues/166
I can register my device and get my token. When I execute php script it gives me “success”: 1 what means it worked, but I cannot receive any notification in my device. If I use FCM console I can receive but no sound is heard.
LikeLike
It should work fine, have you tried using the firebase plugin for this since it will use FCM also?
LikeLike
I won’t use FCM console. It will be a custom backend with a control panel.
LikeLike
Hey and thanks for great tutorial!
I receive notifications on both platforms.
But I want to customize them on android because the notification are received without any sound or vibration.
So I need to add this functionality and add led light that starts flickering to notify despite all my efforts. And badge with counter on icon of application.
LikeLike