PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Android C2DM with PHP and Zend Framework

Note: This article was originally published at Planet PHP on 21 November 2010.
Planet PHP

So you've got a new fancy Android application and you want to be able to send push notifications to the phone. Either for synchronization purposes or for notifications. Since C2DM is fairly new and is currently in the labs it is rather difficult to find code that already handles sending out the notifications correctly.

This article will go through sending a push notification (or message) through the Android C2DM server utilizing PHP in the fashion of a Zend Framework component.

Overview

Sending a message through C2DM can be rather complex as there are fairly strict requirements that Google puts into place. There are several areas that you need to be aware of as well as changes that may happen during the processing of a response. I attempt to encapsulate some of this work in the class handling the sending, however, it is up to the code that sends the notification to properly handle the exceptions thrown. This allows for extremely high flexibility and the ability to hook your own code into this feature.

Requirements

Before we begin there are a few requirements that you will need to have in order to utilize this code to be able to send information to the Android device and create your notification server.

Implementing the C2DM Third-Party Application Server

In order to implement the C2DM Third-Party Application Server we will be utilizing PHP and the Zend Framework. Since Zend Framework already has built-in support for getting the authentication token we will make re-use of that component and simply provide a method for setting the token.

Next we need to ensure that we are properly handling the variances that are coming back from the C2DM server. This can be login based, message based or based on what our user has done on their device. Lets get to the code so we can dissect what needs to happen.

The Library

This library does not have includes in it as we utilize autoloading, if you need includes it is fairly easy to add them all in. This is going to be a lot of code - beware.

library/Zend/Service/Google/C2dm.php

/** * Service Google C2dm * Implementation for Android Cloud to Device Messaging * * @category Zend * @package Zend_Service */ class Zend_Service_Google_C2dm { /** * @var string */ const C2DM_SEND_URI = 'https://android.apis.google.com/c2dm/send'; A /** * @var string */ const AUTH_SERVICE_NAME = 'ac2dm'; A /** * @var string */ protected $_defaultPostUri = self::C2DM_SEND_URI; A /** * @var Zend_Http_Client */ protected $_client; A /** * @var string */ protected $_loginToken; A /** * @var array */ protected $_options = array"/

Truncated by Planet PHP, read more at the original (another 81974 bytes)