Simple Android C2DM
10th Sep 2011
As I mentioned in my previous post, Learning Android didn’t cover a couple topics, and one of them is Cloud to Device Messaging, or push notifications. When applications are getting data from the internet, there are two ways to keep the data fresh. First is called polling. It means that the app initiates a connection to the server at set intervals to see if there are new data. The problem is determining the polling frequency. Poll too often, you waste a lot of batteries without always getting new data. Poll too rarely, then you risk not getting new data in a timely fashion. The alternative is called pushing, or push notifications (iphone users should be familiar with the term). Instead of the client initiating a connection, the server sends a data packet to the client whenever there is new data, then the client reacts to it. Because there is some overhead to maintain a persistent connection to the server, rolling out a push notification service isn’t a trivial task, but google has done that for us! It’s called Cloud to Device Messaging (C2DM). We piggy back off of the connection that android maintains for gmail, google voice, gchat etc, and register our app to be “waken up” only when the server pings us. Note that the server doesn’t actually send the new data, it only sends an alert that new data is available. This keeps the ping packet small so there is less overhead. It’s up to the client app to receive the notification and then go to the server to retrieve the fresh data. In this post I will explain how to setup this service for your app. I will assume that you went through “Learning Android,” or at least have a basic understanding of the building blocks of Android programming. For the sake of keeping this post under a tolerable reading length, I will only go over the mechanisms. I have checked in a sample c2dm app that’s commented in my github repository, so clone the repository to see the whole picture. I also included a small ruby script to mimic a web server sending c2dm packets to the client device, this way you can debug your implementation without needing to setup a server. By the end of this post you should have an app that you can install on your phone or emulator, and then a way to send it push notifications without requiring any server side coding!
Isaac Liu is currently a Ph.D student at the