Reader small image

You're reading from  Asynchronous Android Programming - Second Edition

Product typeBook
Published inJul 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785883248
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Steve Liles
Steve Liles
author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles

Right arrow

Chapter 10. Network Interactions with GCM

In previous chapters, in order to update any kind of dynamic data that our examples required, we explicitly initiated a connection to a remote server, waking up the network radio and other resources required to perform the network operation. The application might fetch either fresh data or exactly the same data if nothing has changed since the last fetch.

Although this communication-fetching model might work for most use cases, it could consume battery resources and internet bandwidth in vain when the data does not change often.

This technique, commonly known as data polling, may also increase the server load when a great number of clients try to fetch or verify whether any data has changed.

An alternative to the polling technique is data pushing. In this technique, the server tells the application when new data is available or when the data has changed. When the data consumer (application) gets notified, it will initiate a new interaction with the...

Introduction to GCM


Since every network interaction with your server could wake the wireless radio interface up, on a device with limited energy resources it is crucial to minimize the number of times that your application tries to hit the network to sync data.

For applications that require regular updates and up-to-date data, like a messaging application, polling in the background by setting an alarm for every x minutes, then waking up the radio and downloading your data could drain the battery in a matter of hours.

Figure 1 - Polling data from remote server

The GCM offers us a platform to efficiently deliver notifications, with less than 4096 bytes, when there is new data to be consumed or to synchronize. This interaction model reduces the network interactions, and there is no need to constantly poll the server to discover data changes.

Beyond the ability to dispatch downstream messages from your server (using HTTP or XMPP protocol messages) to your Android application, the GCM framework...

Setting up and configuring GCM for your application


To setup Google Cloud Messaging on your application you will have to register with GCM and set up a Google API Project on your Google Developers Console (https://developers.google.com/mobile/add):

  1. First pick Android App Platform

  2. Specify your application name

    Example: Asynchronous Android

  3. Supply your application package name

    Example: com.packpublishing.asynchronousandroid

  4. Select Cloud Messaging Services and Enable Google Cloud Messaging

  5. Generate the configuration files and download the JSON configuration file google-services.json to your computer.

  6. Save your credentials (Server APIKey, SenderId) to authenticate with the GCM platform

Once you have registered your application with GCM, get the google-services.json configuration file and copy the file into the app/ or mobile/ directory of your Android Studio Project.

Next, add the Google Play Services SDK to your project level and app-level <PROJECT_DIRECTORY>/build.gradle file and rebuild...

Receiving downstream messages


With the basic blocks required to set up the GCM client already in place, in our first GCM example we will send a simple downstream message through the GCM Platform and print it as a notification on the Android Notification drawer.

To handle GCM messages, we will have to implement a service that extends from GcmListenerService and override the onMessageReceived(String,Bundle) method. Since GcmReceiver extends WakefulBroadcastReceiver, it is guaranteed that the CPU is going to be awake until the service completes the delivery.

Our GcmListenerService subclass will receive a message from GCM and create an Android Notification as soon as it receives it.

public class NotificationGCMHandler extends GcmListenerService {

  public static final int NOTIFICATION_ID ="GCMNotification".
                                            hashCode();

  @Override
  public void onMessageReceived(String from, Bundle data) {
	    
    String msgType = data.getString("type");

    // Notification...

Receiving messages from topic


The downstream messages allow us to send send short (4KB) messages to alert the user of new updates, new content or even reminders.

A downstream message is a one-way communication channel where the users can receive messages, but they cannot respond to them directly or take any immediate action.

To build interactive experiences, such as a chat system, we will have to support a bidirectional communication where the user can receive downstream messages and also send upstream messages to other devices or groups of devices.

In our next example, we will build a simple group messaging system based on the GCM upstream messaging and topic messaging features. The group messaging system will allow multiple devices to publish text messages to a shared message channel.

GCM topic messaging allows your backend server to send a message to devices that have a particular topic. Once the GCM receives a message to a particular topic, it will route and deliver the message to the...

Sending upstream messages


Although we are able to receive the chat group messages, we are not able to interact with the message stream from the application. Additionally, to send and process upstream messages with the GCM platform, an application server that implements the XMPP Connection Server protocol is required to connect to the GCM servers and receive upstream XMPP messages.

To deal with our group messages we built a very basic XMPP server that processes the upstream messages from the device and forwards the message to the topic message.

The basic XMPP Server source code is available from the Packt Publishing website. Grab it from the Packt website, and, before you run it, update the static fields with your SenderID and your ServerKey in the GCMServer.java class file.

private static final String SENDER_ID = "<YOUR_SENDER_ID>"; 
private static final String SERVER_KEY = "<SERVER_KEY>";

The server will connect to the GCM platform, initiate a XMPP session, and process all the...

GcmListenerService delivery callbacks


In some situations, when there is no connectivity with the GCM servers due to lack of network connectivity, the message could remain on the local queues for a long period of time. So, in order to discard a message that remains on the queue without being sent to the GCM Service within the time specified, the GoogleCloudMessaging API provides an additional send method that could receive a TTL (Time to Live) time to set the message expire time:

void send (String to, String msgId, long timeToLive, Bundle data)

This works great when you have messages that are only relevant if they arrive within a certain time frame. With a time to live of 0, we'll attempt to send and return an error immediately if we're not connected. This situation does not apply for our example, so we will keep the original code with the send method that does not discard an old unsent message.

It is important to understand that the application GCM client is only able to queue a maximum of...

Executing tasks with GCM Network Manager


Beyond the messaging framework, the GCM library comes with GcmNetworkManager, an API that allows us to efficiently schedule recurrent or periodic tasks on all the devices that run API level 9 (Android 2.1) and above. For devices running on API Level 21 (Lollipop) and above, GCM Network Manager uses the native JobScheduler API internally, covered in detail in Chapter 7, Exploring the JobScheduler API. In the same way as the JobScheduler API, it will try to batch the jobs and reduce the number of wakeups from idle state to improve the battery life of your user's device.

Moreover, with GCM Network Manager we are also able to set criteria that should meet to start the job execution, such as when the device is in a charging state or an unmetered WIFI connectivity is available. Although the GCM API offers us the same criteria offered by the JobScheduler API, it can be used on older and newer devices that have Google Play Services installed.

So, before you...

Summary


In this chapter we learned how to send and receive data using a battery-efficient communication channel provide by GCM Platform.

First, we learned the differences between polling and push/pull communication techniques to interact with network servers. The push and pull messaging used by GCM is able to reduce the battery efficiency of your application by avoiding redundant server queries to keep the user's data up to date.

In the meantime, we learned how to setup and configure the GCM library on our application. To interact with Google Services, our device obtained a instanceID and registration token to authenticate and identify our device on the GCM service.

Next, we learned how handle notification messages and topic messages on our application and we interacted with a custom XMPP server using GCM upstream messages. At the same time, we built group chat system that is able to aggregate messages from different users in a unified stream of messages displayed on the screen.

Finally, we...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Asynchronous Android Programming - Second Edition
Published in: Jul 2016Publisher: PacktISBN-13: 9781785883248
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles