Java – Realtime (almost) bidrectional communication in Java

androidjavasockets

I will explain the context of the problem first. For a University project I'm going to implement an Android application. The Android application (and others) will be able to send data to a remote source, that remote source will also be able to send messages to the Android applications. For example the messages may be "apply configuration x", "what is your status". I want the remote source to be able to send these messages to:

  1. Reduce overhead. I don't want the Android devices sending data when its not necessary. This uses data and power.
  2. So that I can scale it, for example version 1 might allow you to check what value x is on the Android applications, version 2 might let you check what y is etc.

I have looked at implementing this using Sockets in Java. Having the Android application talk to the remote source is easy. I configure the router (port forward) and everything is OK. The problem is having the remote source to talk to the Android application. They may be using public WiFi hotspots, have their 3G on etc, I wouldn't be able to address the device directly via sockets right?

The approach to solving the problem is not that common I believe, which makes me believe I'm trying to do something that shouldn't be done. Can anyone shed some light on this and offer me some guidance?

Many thanks.

Best Answer

As you say, typically it is very difficult or impossible to establish a socket connection originating at a central server and attempting to connect to mobile devices. Instead, what you can do is originate the connection at the mobile device, connect to the central server, and leave the socket open waiting for a command from the central server. Of course the first thing your Android code would do on connection is identify itself to the central server, so the central server knows who it is talking to.

Fortunately, Google has already done this for you in Google Cloud Messaging for Android:

Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).