Grails Android GCM Plugin

October 31, 2012 at 13:27

Note: this is the english version of the post that I published in Mindfood, written in spanish.

As a result of the two first OSOCO’s hacker fridays, Adrian Santalla and I published the Grails Android GCM Plugin (among other things 😀 ), whose source code can be checked out from Github.

This small plugin provides your Grails application with access to Android GCM (the service that Googe uses for Android push notifications) through a service that you can inject in your application artifacts.

The plugin is published in the Grails plugins repository, so installing it is as easy as invoking the install-plugin command. After that, you should be able to use the androidGcmService in any of your services, controllers, etc. The following example ilustrate the most simple case of use:

$ grails create-app AwesomeApp 
$ cd AwesomeApp
$ grails install-plugin android-gcm
$ grails create-controller Cool
$ cat > grails-app/controllers/awesomeapp/CoolController.groovy << EOF
package awesomeapp

class CoolController {

    def androidGcmService

    def index() {  
        render androidGcmService.sendMessage(
                aMessageKey : 'The message value for the key aMessageKey', 
                anotherMessageKey : 'The message value for the key anotherMessageKey' 
            ['anAndroidDeviceToken', 'anotherAndroidDeviceToken'],
            'youShallCollapseThisMessage', 'yourGCMAPIKeyProvidedByGoogle'      
$ grails run-app
$ $ wget -O - http://localhost:8080/AwesomeApp/cool/index 2> /dev/null
MulticastResult(multicast_id=8596196938900195177,total=2,success=0,failure=2,canonical_ids=0,results: [[ errorCode=InvalidRegistration ], [ errorCode=InvalidRegistration ]])

As you can see, the controller tries to send a message (that on its behalf if formed by two messages, each with its own key and value) to two Android devices, marking the message as collapsed and passing the GCM API key provided by Google. When the result is rendered, a MulticastResult is shown (since we are sending the message to multiple devices) with the result of the message sending (that, in this case, is an InvalidRegistration error, since we are using made up Android devices 😀 ). Please note that ff you want to try this example, remember to substitue yourGCMAPIKeyProvidedByGoogle with a valid API key, otherwise the underlying Android API will fail with a pretty null pointer exception 🙁 .

To see a full list of the provided methods and the available configuration options, check the project README at Github.