×
Namespaces

Variants
Actions

Implementing Notifications in Nokia X with Azure Mobile Service

From Nokia Developer Wiki
Jump to: navigation, search
Featured Article
11 May
2014

This article explains how to send notification to a NokiaX device using Azure Mobile Service.

Contents

Introduction

This article will explain on how to register a device to azure mobile service and send notifications to the device.

Implementation

Getting Started with Azure Mobile Service

A very good article on getting started with Azure Mobile Service for Android is available here. We would be utilizing table, custom api and scheduler features of Azure Mobile Service in this article. A free version of Azure Mobile Service is available with 20mb free database. So we can run a basic notification server free of cost.

Preparing Azure Mobile Service to Save Device Registration Ids

Create a new Azure Mobile Service

Newmobileservice.png Newmobileservicefinish.png

Creating a table to store registration ids in back-end

Go to data tab in mobile service dashboard and click on Add a Table

5-7-2014 1-16-21 AM.png

Create a new table with name notification. Change insert, update, delete & read permissions to Only Scripts and Admins, since this table would accessed in the back-end only to register device and send notifications.

5-7-2014 1-17-08 AM.png

Create a custom api to register a device with mobile service

Go to api tab in mobile service dashboard and create a new Custom API with name notification.

5-7-2014 1-00-46 AM.png

Add the below script to the notification api

exports.post = function(request, response) {
var registrationId = request.body.registrationId; //We would pass this from our android app after getting the nokia notification registration id
var deviceId = request.header('X-ZUMO-INSTALLATION-ID'); //This will be sent by mobile service sdk automatically unique for each device
var notificationTable = request.service.tables.getTable("notification"); //Getting a reference notification table we created earlier
notificationTable.where({deviceId: deviceId}) //Checking whether a registration id is saved in the table for the device
.read({
success: function(results){
if(results.length === 0){ //If no records found we proceed with adding a entry to the table
notificationTable.insert({ registrationId: registrationId, deviceId: deviceId }, {
success: function(notificationObj)
{
response.send(201, notificationObj);
}
});
}
else{ //If a record is already found for the device we update the registration id and save it
results[0].registrationId = registrationId;
notificationTable.update(results[0], {
success: function(notificationObj){
response.send(200, notificationObj);
}
});
}
},
error: function(err){
console.error(err);
}
});
};

Getting the NokiaX app ready

We will use the existing code sample NokiaNotificationsHelperLibrarySample to implement this.

Nokiaxcodesamplemenu.png Nokiaxcodesamplelist.png

Download azure mobile service android sdk and extract the contents. Add all the jar files present in the mobileservices folder to the libs folder of the project.

Open PushIntentService.java and import the below packages

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.microsoft.windowsazure.mobileservices.*;

Add private variable to the PushIntentService class

private MobileServiceClient mClient;

Add the below code at the end of the onRegistered method

@Override
protected void onRegistered(final Context context, String registrationId) {
Log.i(TAG, "Device registered with ID \"" + registrationId + "\"");
CommonUtilities.displayMessage(context, getString(R.string.push_registered, registrationId));
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("NID", registrationId);
clipboard.setPrimaryClip(clip);
CommonUtilities.displayMessage(context, "Registration ID was copied to the clipboard.");
 
try {
mClient = new MobileServiceClient(
"<Your mobile service url>",
"<Your mobile service api key>",
context
);
JsonObject obj = new JsonObject();
obj.addProperty("registrationId", registrationId); //This corresponds to the req.body.registrationId of custom api
mClient.invokeApi("notification", obj, new ApiJsonOperationCallback() {
 
@Override
public void onCompleted(JsonElement arg0, Exception arg1,
ServiceFilterResponse arg2) {
CommonUtilities.displayMessage(context, "Device registered with mobile service");
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Run the project in a emulator or device.

Runnokiaxnotificationemulator.png Runnokiaxnotificationemulatorregister.png Runnokiaxnotificationemulatorregistersuccess.png

Now a new entry would be present in the notification table in mobile service containing the regisration id and the device id.

Mobileservicenotificationsaved.png

Send a push notification from mobile service to device

For this we utilize the scheduler feature of mobile service. Using a scheduler we can either run a script at specified interval or manually whenever required. Create a new scheduler with name nokiaxnotificationtest and set the schedule to On Demand.

Mobileservicenewscheduler.png

Add the below code to the scheduler script

var request = require("request"); 
function nokiaxnotificationtest() {
var notificationTable = tables.getTable("notification");
var notificationData = { payload: "New notifcation on " + (new Date()) }; //Sample payload
notificationTable.read({ //Read all the registration ids present in the table
success: function(results){
if(results.length > 0){
var registrationIds = [];
results.forEach(function(item){
registrationIds.push(item.registrationId); //Composing all registration ids into a id array
});
request.post({
url: "https://nnapi.ovi.com/nnapi/2.0/send",
headers: {
"Content-Type" : "application/json",
"Authorization" : "<Your nokia notification api key>"
},
body: JSON.stringify({ registration_ids: registrationIds, data: notificationData })
},function (err, resp, body){
console.log(body);
});
}
}
});
}

Click Run Once to run the script

Noxiaxnotificationreceived.png

Sending notification to a particular device

To send notification only to a particular device change the above script as below.

var request = require("request"); 
function nokiaxnotificationtest() {
var notificationTable = tables.getTable("notification");
var notificationData = { payload: "New notifcation on " + (new Date()) }; //Sample payload
notificationTable.where({deviceId: "<some device id>"}).read({ //Read the registration id of a particular device
success: function(results){
if(results.length > 0){
var registrationIds = [];
results.forEach(function(item){
registrationIds.push(item.registrationId); //Composing all registration ids into a id array
});
request.post({
url: "https://nnapi.ovi.com/nnapi/2.0/send",
headers: {
"Content-Type" : "application/json",
"Authorization" : "<Your nokia notification api key>"
},
body: JSON.stringify({ registration_ids: registrationIds, data: notificationData })
},function (err, resp, body){
console.log(body);
});
}
}
});
}
This page was last modified on 12 May 2014, at 15:27.
97 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×