READ THIS FIRST

Update: 3-4-2016: If you're finding this blog and looking for information related to Azure Mobile Services, I'd strongly recommend checking out Azure Mobile Apps. Azure Mobile Apps is a new version (consider it a v2) of Azure's mobile backend support. All of the same features of Azure Mobile Services are there, with a lot of other very cool features to go along. You can read more about Azure Mobile Apps, and how to transition from Azure Mobile Services, here.

Windows Azure Mobile Services Since this was posted, Microsoft has released the official Android SDK and support for Mobile Services. You can read more about the release and how to use the Android SDK here.

As of writing, we’re still working on the official Android SDK for Windows Azure Mobile Services.  However, as I pointed out during a presentation at CodeMash earlier this year, one of the Microsoft MVPs, Sasha Goldshtein, created an unofficial Android SDK.  This SDK, which is available on GitHub, includes some sample documentation to get you started with data storage, authentication, as well as push notifications.  In fact, just about everything you can do with the official iOS, Windows Store, and Windows Phone SDKs can be done with Sasha’s SDK.  He really has done a great job of putting together something that can be used right now.  Today I’m going to take you through taking an existing project and adding support for data storage, authentication, and push notifications into it.  If you want to go straight into the finished code, you can download the GitHub repo here.  Once you have it, take a look at the source/end directory for the completed code.  Just make sure you set the proper settings (URL, Application Key, push token, etc) to match your Mobile Service and Google API info before running.

Getting the SDK

The first step today will be to pull down Sasha’s SDK from GitHub.  I recommend doing this by cloning the URL for his repo.  Once you’ve pulled down the repo, go into Eclipse and go to File and then Import.  In the window that comes up next, choose Existing Projects into Workspace and hit NextBrowse to the directory containing the SDK and click Finish.  You should now see WAMS-Android as a project in Eclipse.  If you expand the project and it’s src folder, you should see Sasha’s namespace net.sashag.wams.android.  Now you’re ready to start with the app.

The starter app

In order to make things line up with the tutorials we already have for the other platforms, I’ve actually created a Todo List application that will run on Android but doesn’t persist data at all.  You can pull this Todo List application from the GitHub repo I created for this post.  Once you pull it down, you’ll want to look in the source/start directory for the initial project.  Running this app will give you a very simple todo list that let’s you add new items:

Todo List before using WAMS

There is also a complete button next to each item but that currently doesn’t do anything.  If you shut down and rerun the application, you’ll notice that your todo list is blank again.  This is because we’re not currently persisting this data anywhere.  Handling that will be the first step in using Mobile Services. 

What if we were starting with our own project

Using the sample project skips one very important step: adding a reference to the WAMS-Android library.  If you were going to start with your own project, you’d want to right click on your project in the Package Explorer and go to Build Path and choose Configure Build Path.  In the build path window, select the Projects tab and then hit Add.  Find WAMS-Android and check it and click OK.  Before closing the properties for your project, click Android on the left side and at the bottom of the panel, next to where it says Library click the Add button.  Select WAMS-Android in the window that comes up.  Click OK and now the Library panel should look like this:

Adding sdk as library

Creating your Mobile Service

If you haven’t already done so, make sure you spin up a new Mobile Service in the Windows Azure portal.  I’m not going to talk a lot about doing this in this post because I already have.  If you need assistance with creating a new Mobile Service, or where to get the Application Key or create the Todo Item table we’ll need later on, check out this post from a few months ago.  You can ignore all of the code parts of that post and just focus on the process to create a new Mobile Service, get the key, and create the table.  When you’ve done with that, proceed on.

Adding Mobile Services settings

The next step we need to take is to add a few configuration settings needed just to connect to our Mobile Service.  Open up the res/values/strings.xml file.  We already have a number of values in here that are used for text display in our app.  We’re going to add two new string values that the SDK automatically looks for: the Mobile Services URL and the Application Key.  Following the step above this, you should be able to get both of those values and then enter them into your file like this:

Now that that’s done, we can move on to working with data.

Data annotations

In order for the SDK to understand how to serialize and deserialize our data, we need to put some annotations on our TodoItem class.  Open up src/com.cmr.wams_test.TodoItem.java.  Currently, this class is just a simple representation of a todo item.  We need to mark it so we know what table it matches up with on the server side, what the column names should be, as well as adding in an ID member which is added by default to every table in Mobile Services.  When we’re done, our TodoItem class will look like this:

The first annotation is the DataTable one.  This tells the SDK what table this class matches up with in Mobile Services.  We then have two DataMembers.  This is how we tell it what the field names should be when they are sent to, and received from, our Mobile Service.  Lastly, we have Key which is needed for all classes that are tied to a table in Mobile Services.

Adding a client and inserting items

Now let’s actually instantiate the objects we’ll use to talk to Mobile Services and insert some items.  Open up src/com.cmr.wams_test/TodoList.java.   The first thing we’re going to do is add some new private variables:

Here we’ve created a MobileService to get access into our Mobile Service and a MobileTable (that is tied to our TodoItem class) to handle all of the operations on our table.  Now let’s jump down to the onCreate method and instantiate those variables:

Nothing complex going on here.  Finally, let’s alter the onClick method that is assigned to the + button:

First we’ve removed the calls to notifyDataSetChanged and to clear the EditText.  We’ve then added a call to todoTable’s insertAsync method.  This call takes in the new TodoItem instance and a MobileServiceCallback.  The callback has a errorOccurred method that is called if there is an error and a completedSuccessfully that is called on success.  Notice that the success method has a TodoItem as a parametere.  This is because any calls to insert will return to you the updated item from the server.  We can then add that updated item to our local ArrayList and then notify the dataset that it’s data has changed and finally clear the EditText.  Now when you run your application and add some todo items, you should be able to go to the data tab in the Windows Azure portal and see those items:

Saved items in emluator

And if we look in the portal:

Saved Items in Portal

Now we can work on loading the items back in on launch.

Loading data

We’ll start by adding a new method, LoadTodoItems, to our class:

This method calls the todoTable’s where method and says that we want to select all of the items where the complete field is false and says we want to do it asynchronously.  We are passing into that a MobileServiceCallbackWithResults that also has an error and success method.  In the success method, we are setting our internal array (todoItems), creating a new TodoArrayAdapter, and then setting that as the adapter for our ListView.  The last thing you’ll need to do is add a call to this method into your onCreate method.  Now when you run your app, after a second or two you should see the todo items you added before reappear.

Updating data

Now that we’re able to save and load data, let’s take a crack and updating the todo items when the user taps the complete button.  Add the following method into the TodoList class:

This method will loop through the todo array and find the correct item by it’s text.  It will then call the todoTable’s updateAsync method.  When that call returns successfully, we remove the item from the array and then notify the adapter that the data set has changed.  Now, open up the TodoArrayAdapter and add a call to todoList.markItemComplete(text1.getText()); to the OnClickListener near the bottom.  Now when you run your app and tap the complete button, it should update the record on the server and remove it locally. 

Adding push notifications

The next feature we’re going to implement is push notifications using Google Cloud Messages.  Doing so requires us to do a little work in the Google API Console.  Start by navigating to https://code.google.com/apis/console.  If you already have projects set up, then you should see a drop down in the top left (right under the Google apis text) that will allow you to create a project.  I’ll name my project Android-WAMS and hit Create Project.  The next screen you see should be a list of Google Services (if it isn’t, hit the Services link on the left side).  Find Google Cloud Messaging for Andorid in the list of services and click the OFF button so it switches to ON.  With that done, go back to the top left and click on API Access.  In the next screen, click the Create new Server key… button and leave the IP addresses box blank hit click Create.  This will create a new key with Any IP allowed below it’s API Key.  You’re going to need this key in a little bit.  Additionally, you’ll need to make a note of the project ID which you can get from the URL of the browser you’re in.  For example, the project I just created has this URL: https://code.google.com/apis/console/b/0/?pli=1#project:64846990266:access.  So my project ID is 64846990266.  Return to Eclipse and open the res/values/strings.xml file.  We’re going to add a new value with the name mobileServicePushSenderId and the project ID as it’s value:

<string name="mobileServicePushSenderId">64846990266</string>

Next open up the AndroidManifest.xml file and add the following in above the Internet permission:

Here we’ve requested the necessary permissions to use GCM (they are still using the old name C2DM) as well as requested WAKE_LOCK permission.  Notice that I’ve put my app’s package name in several spots where it shows up as com.cmr.wams_test.  If you are putting this into your own application, make sure this matches your package.  Now put the following below the </activity> and before the </application> tag:

Here we’re creating a receiver to handle receiving registration messages and the actual messages.  Sasha has done some great work here in that we don’t have to implement our own receiver but can just use the one he built in (or override it if we choose to).  Again, notice that I have used my package name in the category.  The last thing we need to do in our application’s code is to add a call to register for push notifications.  I’ve done this by putting the following code into TodoList’s onCreate method before I’m calling the method to load the todo items:

msClient.registerPush();

Now let’s go back to the Windows Azure Portal and make the necessary changes there.

Setting up the server side

In the portal go to the Data tab and click the CREATE button at the bottom to make a new table.  Name this table pushChannel and leave all of it’s permissions as the defaults.  Now open the pushChannel table and go to it’s SCRIPT tab and drop this script in for it’s Insert method:

This script will handle deduplicating registration IDs so that we don’t end up with the same registration ID in the table multiple times.  Now, save that and then switch over to the TodoItem table and set it’s insert script to be this:

This script will first insert into the database and then, on success, will call the sendGcmPush method.  The push method will pull all of the registration IDs from the pushChannel table and loop through them and send a push to each one.  Notice that I’ve put my API key (as I mentioned above) in for the Authorization Key.  While there isn’t the same “one line” push code we’ll eventually have with official support later on, we can still trigger a push by just doing a web request to the Google API.  Now run your app again and add a new Todo Item.  You should see a toast popup at the bottom of the app:

Pushing with Android

Here we can see that the push notification that came back had the text I put in, test push, along with the from push text we added in the insert script.

Adding authentication

The last feature we’re going to add into our application is authentication.  We’ll do this to facilitate making sure every user has their own todo list.  Let’s start by returning to the portal and going to the TodoItem table and then going to it’s Permissions tab.  Currently, all of the permissions are set to Anybody with the application key. Change all of these to be Only Authenticated Users and save.  Now, rerun your application.  After a moment, you should see an error message saying Error Fetching Objects.  This is happening because we’ve told our Mobile Service that any calls to TodoItem need to have an authenticated user token coming across in it’s headers.  We’re going to solve this today by adding in Twitter authentication.  To start, we need to go to the Twitter Development portal at http://dev.twitter.com.  After logging in, use the drop down in the top right to select My Applications.  In the top right of the next window, click the Create a new application button.  In the next page’s form, enter whatever you want for the Name and Description of your app.  For the Website and Callback URL, enter the URL of your mobile service.  You can get this by going to the Dashboard tab in the portal.  Once there, the URL will be available on the right side.  For my service, it’s http://unofficial-android.azure-mobile.net.  After you fill out the captcha and agree to the terms of service, you’ll be taken to the details page for your app.  On this page you’ll see a Consumer key and Consumer secret.  Copy these values and go back to the portal and open the Identity tab.  Under the twitter settings, paste these values in and save your changes.  Your mobile service is all set on the server side to allow authentication.  Now we just need to handle things in our app.  Open up TodoList and go to the onCreate method.  We’re going to replace the call to LoadTodoItems() with the following block of code:

Here we’re checking the msClient to see if the user is logged in.  If they are already logged in, we just call the load method.  If not, then we call the login method on msClient and specify that we want to login to Twitter using the MobileServiceAuthenticationProvider.Twitter variable.  When the success method is called we then load the todo items.  Now when you run your app, you’ll see the Twitter web login show up in a web view:

Twitter Login

After logging in, you should see the todo items load up. 

Tying items to users

The next step we need to take in order to make the todo lists custom for each person is to make a server side script change.  Go to the portal and open the Data tab.  Go to the TodoItem table and go to the Insert script.  Add this to the first line of your insert method:

item.userId = user.userId;

Now when you save a todo item, you’ll see a new column has been added to the table and my Twitter ID is saved:

Saved User IDs

Querying by user ID

The last step today, is to only pull down the todo items for my user ID.  We can do this in two ways: from the client or from the server.  We could always put another where clause on the call to todoTable.where() in the LoadTodoItems method, however, we don’t want to trust the client.  It’s always possible could figure out the calls that are being made and alter them to not include that where clause.  So instead, we’ll make the change on the server.  Go to the portal and open the TodoItem table’s Read script. Before the call to request.execute(), put this line of code in:

query.where({userId : user.userId});

Save that and rerun your app.  Now you should only see the single todo item that was saved with my Twitter ID.  If I were to run the app under a different user, I wouldn’t see any todo items.

Conclusion

Today we walked through quite a bit and learned how to use Sasha’s unofficial Android SDK for Windows Azure Mobile Services.  We went through saving and loading data, handling push notifications, and authenticating.  Thanks to Sasha’s herculean efforts, you have access to everything that the unofficial SDKs can do with Mobile Services.  In time, an official SDK will be released and I’ll update this article to point you in that direction.  For now though, you can use this SDK and rest assured that things won’t change on the server side even if you have to modify a few things for the official SDK (plus the calls to GCM will be made easier).  You can access the completed application source code at this GitHub repository.  The finished app is under source/end and the server side scripts we used are available under source/scripts.  You’ll need to set the API settings in the strings.xml file in addition to setting up your Mobile Service for Twitter auth.  Lastly, make sure you put your own Google API key in the push script.


Chris Risner