What if, however, we want to communicate with the devices in close proximity without bothering about installing apps and creating accounts? The Nearby Messages service from Google does just this. Read on to see it in action.

After a decade of the smartphone era, we are equipped with various means of communication. We have Facebook, Instagram, text messages and simple phone calls for distance communication, as well as NFC, barcode/QR code scanning, and even IR blasters for closer range. 

What if we want to communicate with the devices in our vicinity, for example, to easily share a file with everyone in the room during a meeting? This is where Nearby Messages comes into the picture.

What are Nearby Messages?

Google Nearby, first presented in 2015, is a service which allows for the exchange of data between devices which are in close proximity of one another. Unlike most of the other communication solutions, Nearby Messages doesn’t require you to install any app, create yet another account, share your phone number, and so on. It works in the publish-subscribe model and it has coverage within the range of Bluetooth (I have personally managed to use it with devices that were 20-ish meters apart). It combines Bluetooth, Bluetooth Low Energy, WiFi, and… ultrasound (how cool is that?) to establish and send data. It’s available for both Android and iOS. 

How does it work?

The whole idea might sound like magic but, in reality, it’s very simple. Let’s consider this example: there are two devices, A and B. How do they communicate using Nearby Messages? Here’s what the whole process looks like in  a nutshell:

  1. Device A (the publisher) makes a request to the server to assign a token to a message that the device wants to send. Then, the publisher makes the token detectable to devices nearby.
  2. Device B (the receiver) pairs its subscription with a token. Then, the receiver sends its token to the publisher and detects the publisher’s token.
  3. When both devices detect the same token, the message is sent from A to B.

What is important, the Messages are not exchanged directly between devices; they are sent through Google servers. When one device detects another, it turns to the Google Cloud and says, “Hey! I’ve found a device with this particular token, please give me the message that is associated with it”. Internet connection is required on both devices in order for Nearby Messages to work.

Moreover, Nearby Messages is meant to be used to exchange small packets of data (up to 100 kB). Also, all messages are public (like a broadcast), meaning that the publisher cannot tell the server, “This device should be able to see me, and that one should not”.

There is a way, however, to limit the range of your messages. You can use only ultrasounds for the broadcast process; messages are then only available to the devices within a couple of meters from the publisher.

“Show me the code!”

Enough theory… let’s move on to the practical element! We’ll start by analyzing this simple application which showcases Nearby Messages.

Nearby message

To use the Nearby Messages API, you will need an API key. To get one, follow the instructions here (Step 3: Get API key).

Google made this API very easy to integrate with Android applications; it only takes about 10 lines of code.

  1. Add Nearby dependency to gradle.build:
compile 'com.google.android.gms:play-services-nearby:<version>'

2. Add the API key to the manifest under the <application> tag:

<meta-data
   android:name="com.google.android.nearby.messages.API_KEY"
   android:value="API_KEY" />

3. Publish and subscribe:

Nearby.getMessagesClient(<activity context>).publish(message)
Nearby.getMessagesClient(<activity context>).subscribe(listener)

4. Unpublish and unsubscribe:

Nearby.getMessagesClient(<activity context>).unpublish(message)
Nearby.getMessagesClient(<activity context>).unsubscribe(listener)

5. Listen to found and lost events:

The Listener instance used for the /subscribe/ and /unsubscribe/ methods is where your app receives the events which tell you that a device (or a message, to be precise) has been lost or found:

private val messageListener = object : MessageListener() {
      override fun onFound(message: Message?) {
          message?.let {
              Log.d("MainActivity", "Found ${String(it.content)}")
          }
      }
      override fun onLost(message: Message?) {
          message?.let {
              Log.d("MainActivity", "Lost ${String(it.content)}")
          }
      }
  }

As you can see, no runtime checking and requesting permission is needed. It is handled for you by the following user consent dialog.

One more thing that makes Nearby Messages so easy to use is the automatic Bluetooth on/off management.

Keep in mind, however, that Nearby Messages can quickly drain the battery on your device, so make sure to turn it off when you’re not using it.

Playing with beacons

The example above showed how to initiate communication between two physical devices (Android phones, to be exact). Nearby Messages goes a step further and allows you to listen for messages broadcast by beacons when an application works in the background. 

Here’s a real-life example of how that works: an entertainment company launched a campaign in London to promote its recent movie. They placed 50 “Dream Jars” all around the city and built Nearby Notifications into them. As a result, if you had Bluetooth turned on in your mobile device and approached such a “Dream Jar”, you received a promotional notification thanks to the a little beacon magic.   

If you want to start fiddling with beacons and Nearby yourself,  here’s a short cheat sheet:

  1. Obtain a beacon that supports the Eddystone format.
  2. Register the beacon with the Beacon Tool application, providing the Namespace and Instance ID.
Broadcast Profile

Once you are done this, you can modify the subscription code:

1. Create BroadcastReceiver class to handle the incoming messages:

override fun onReceive(context : Context, intent: Intent) {
         Nearby.getMessagesClient(this).handleIntent(intent, object : MessageListener(){
        //override onFound(...) and onLost(...) methods
      }));
}

2. Subscribe to background messages:

val intent = PendingIntent.getBroadcast(this, 0, Intent(this, BeaconMessageReceiver:class.java), PendingIntent.FLAG_UPDATE_CURRENT)
val options = SubscribeOptions.Builder()
          .setStrategy(Strategy.BLE_ONLY)
          .build()
 
Nearby.getMessagesClient(context).subscribe(intent, options)

Messages will now be delivered to the broadcast receiver where one can, for example, show a notification alert. Remember that it will work only if your device has Bluetooth on.

Is this secure?

As mentioned above, the messages sent with Nearby are public, like a broadcast. For this reason, they are not suitable for transmitting sensitive information; they should rather be treated as the communication initiation stage. If you are still worried that other applications can see what you are transmitting and if your application has to handle messages from other apps, Nearby Message has you covered here. The messages are visible in the scope of the same project in the Google Developers Console. Notice the word project here: you can have multiple Android and iOS applications associated with the same project.

Wait, there’s more!

This article covered only Nearby Messages, but Nearby itself is much more than that. If you go to the official Nearby website, you will see that there are also Nearby Notifications and Nearby Connection. With the former, you can receive notifications from the beacons which broadcast website URLs (it is supported natively by Android and iOS) and the latter is similar to Messages but it’s designed to send and receive bigger payloads (audio, photos, etc.) with much greater speed in a peer-to-peer way.

What is in it for you?

Now that you know what Nearby Messages is, when to use it, and how simple it is to add it to your application, you might still be wondering how your business can actually benefit from it. The great advantage of this technology is that it reduces the problem of “how can we start talking?” to a single click of a button. The market is still relatively fresh here: there aren’t that many apps of this type yet (one recent example is the LinkedIn app), so there is space for new projects. Take a closer look and you may be able to build the next social media app, a local chat application or a game.

References

Nearby Messages
Nearby at Google I/O 2016