Windows Azure Mobile Services — Unofficial Android SDK

December 24, 2012

no comments

Windows Azure Mobile Services (WAMS) is probably the most exciting Microsoft technology I have encountered in the last 5 years at least. This is a cross-platform framework that serves as a backend for your mobile applications, taking care of concerns such as data access and storage, user authentication, and push notifications. WAMS is the logical next step after PaaS offerings: it is a complete backend-as-a-service, which takes care of most (if not all) your server-side needs.

For a general introduction to Windows Azure Mobile Services, I recommend that you take a look at the Windows Azure Developer Center, or — a shameless plug — my Windows Azure Conf talk on WAMS.

At the time of writing, WAMS has full support for Windows 8, Windows Phone 8, and iOS. On these platforms, the WAMS client library provides classes and methods for accessing data tables on the server, for authenticating the user with Microsoft Account, Facebook, Twitter, or Google, and for sending push notifications from the cloud to all connected devices.

There is an obvious gap here: Android. Until such time that the WAMS client library is officially ported to Android, I decided to implement my own unofficial SDK that currently handles data access and push notifications in a fairly seamless fashion. In this post, I wanted to give you a general idea of what it means to develop an Android application that uses WAMS and my unofficial library.

First things first: you have to get the library code from GitHub. What you get is an Eclipse library project that you can add to your workspace and add a reference to it from your Android application.

Before you start writing client-side code to access WAMS, you need to create a mobile service and create a couple of tables. The easiest way to do so today is by using the Azure cross-platform command-line tool, azure, which you can install using ‘npm install azure’ and ‘npm install azure-cli’ if you have Node on your development machine.

Once you have configured the azure command-line tool, go ahead and create your first mobile service with a couple of tables:

$ azure mobile create
info:    Executing command mobile create
Mobile service name: myfirstmobileservice
SQL administrator user name: user
SQL administrator password: **********
Confirm password: **********

$ azure mobile table create myfirstmobileservice message
info:    Executing command mobile table create
+ Creating table                                                               
info:    mobile table create command OK

$ azure mobile table create myfirstmobileservice pushChannel
info:    Executing command mobile table create
+ Creating table                                                               
info:    mobile table create command OK

After creating the service, run the following command to obtain the service URL and application key. You will need these later:

$ azure mobile show myfirstmobileservice
info:    Executing command mobile show
+ Getting information                                                          
info:    Mobile application
data:    status Healthy
data:    Mobile service name myfirstmobileservice
data:    Mobile service status ProvisionConfigured
data:    SQL database name myfirstmobileservice_db
data:    SQL database status Linked
data:    SQL server name YOUR_SERVER_NAME
data:    SQL server status Linked
info:    Mobile service
data:    name myfirstmobileservice
data:    state Ready
data:    applicationUrl
data:    applicationKey YOUR_APPLICATION_KEY
data:    masterKey YOUR_MASTER_KEY
data:    webspace EASTUSWEBSPACE
data:    region East US
data:    tables message,pushChannel
info:    mobile show command OK

Now you’re ready to start working with data and push notifications in your Android application. Suppose that you want to insert new messages into the message table created previously. To do that, you define a class that represents a message, and use annotations from the WAMS client-side library:

public class Message {
	@Key public int id;
	@DataMember public String from;
	@DataMember public String text;

	public Message(String from, String text) {
		this.from = from;
		this.text = text;

Now, you can connect to the message table and insert a new message, as follows:

MobileService mobileService = new MobileService("", "YOUR_APPLICATION_KEY");
MobileTable<Message> messageTable = mobileService.getTable(Message.class);
Message message = new Message("Sasha", "Hello!");

There is also support for asynchronous operations, but I’ll leave that to you to explore. To verify that the message was inserted, check your table contents with the command-line tool:

$ azure mobile data read myfirstmobileservice message
info:    Executing command mobile data read
info:    mobile data read command OK

To query data from your mobile tables, you can use the query API. The queries you specify are delivered all the way to the Windows Azure SQL Database instance in the cloud, and you receive only the filtered results. For example, here’s how you can retrieve the latest 30 messages from the user “Sasha” (additional pagination support is available with the skip method):

List<Message> messages = messageTable.where().equal("user", "Sasha").top(30).select();

Finally, let’s move on to the feature I most recently implemented — push notification support. Android push has become much easier with the introduction of the Google Cloud Messaging (GCM) library. My WAMS client-side wrapper makes it a breeze to interact with GCM. First, you should obtain a sender ID from the GCM console. Once you have it, add the following string resources to your Android app:

<string name="mobileServiceUrl"></string>
<string name="mobileServiceApiKey">YOUR_MOBILE_SERVICE_API_KEY</string>
<string name="mobileServicePushSenderId">YOUR_GCM_SENDER_ID</string>

Now, to register for push on the client, all you need to do is:


The library also offers support for a transient push callback that will be invoked when a push notification is received, as well as an intent service you can extend to process push notifications even if your app is not running. For more information on these, take a look at the walkthrough on GitHub.

On the server, to send a push notification to all registered clients that will be displayed in the Android notification area, add a server script resembling the following:

var reqModule = require('request');
var channelTable = tables.getTable('pushChannel');{
	success: function(channels) {
		channels.forEach(function(channel) {
				url: '',
				method: 'POST',
				headers: {
					//TODO: this should be your push API key
					'Authorization': 'key=PUSH_API_KEY'
				json: {
					//You could pipe up to 1,000 registration ids here
					registration_ids: [channel.regId],
					data: {
						"__builtInType": "notification",
						"contentTitle": "Your notification's title",
						"contentText": "Your notification's text",
						"tickerText": "Your notification's ticker text",
			}, function (err, resp, body) {
	            if (err || resp.statusCode !== 200) {
	                console.error('Error sending GCM push: ', err);
	            } else {
	            	console.log('Sent GCM push notification successfully to ' + channel.regId);

Alternatively, if you want to test push notifications from a local app, you can use the following curl command line (without any WAMS intervention):

curl -X POST -H 'Authorization: key=YOUR_PUSH_API_KEY_HERE' -H 'Content-Type: application/json' --data '{ "registration_ids": ["REG_ID_HERE"], "data": { "__builtInType": "notification", "contentTitle": "This is the title", "contentText": "This is the content text", "tickerText": "This is the ticker text" } }'

This walkthrough does not describe every possible feature the client library currently supports, but it’s a good start. For more information, take a look at the docs on GitHub, and stay tuned: I plan to add more features — such as authentication — at some point in the future. (Unless the WAMS team beats me to it :-))

I am posting short links and updates on Twitter as well as on this blog. You can follow me: @goldshtn

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>