Sejal Baraiya
IndiaNIC
Published in
5 min readSep 19, 2017

--

SETTING UP NEW FEATURES OF NEARBY API-BEACONS, MESSAGE

Firstly, just simple introduction about beacons…

What is a Beacon?

Beacons are Bluetooth-transmitters that send some information or advertising data that can be accepted by the smartphones and tablets within the range of the transmitter. For instance, a smart bus stop can transmit, route schedules, a shop can send discount’s information, a museum can air the timetable of exhibitions, and so on. A message transmitted as a notification can contain a link to any web pages.

For the complex operations using beacons, Google developed a number of independent solutions under the unified Google’s Beacon Platform. It includes the Eddystone format, the Beacon Dashboard monitoring, and management system, and the APIs for beacons interaction (like Google Proximity Beacon API, Nearby Messages API, and Places API).

How the Beacons send messages to nearby devices

How the Beacons send messages to the nearby devices?

Nearby Messages API is the API for Android and iOS that scans devices, collects data from the Google Cloud, Beacon information, and the attached data.

Google Proximity Beacon API is the API for beacon management and administration. Briefly, we have Google Cloud where all the beacons are registered by their identifiers. You can use a special Proximity Beacon API or a Beacon Tools app for this purpose.

You can follow a few simple steps and get started with Firebase’s Nearby API for beacons and the messages both. You can go through the steps at https://developers.google.com/nearby/messages/android/get-started site and get all the details you want.

In order to link the project to beacons and see the detail, you can visit the below mentioned link and move further.

Beacon Dashboard | Google Developers

A dashboard to manage your beacons.developers.google.com

Then we need to just put the Nearby messaging code for getting the nearby messages from the devices those are in the Beacon range. You need to use only the Nearby. MESSAGES_API.

private void buildGoogleApiClient() {
if (mGoogleApiClient != null) {
return;
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Nearby.MESSAGES_API)
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.build();
}

Then, you have to use the message listener methods to find the nearby devices and for those out of the range list also.

mMessageListener = new MessageListener() {
@Override
public void onFound(final Message message) {
// Called when a new message is found.
mNearbyDevicesArrayAdapter.add(
DeviceMessage.fromNearbyMessage(message).getMessageBody());
}

@Override
public void onLost(final Message message) {
// Called when a message is no longer detectable nearby.
mNearbyDevicesArrayAdapter.remove(
DeviceMessage.fromNearbyMessage(message).getMessageBody());
}
};

You can add the nearby devices into the adapter and see the list of nearby devices and check the list found by the messageListener:

final List<String> nearbyDevicesArrayList = new ArrayList<>();
mNearbyDevicesArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
nearbyDevicesArrayList);
final ListView nearbyDevicesListView = (ListView) findViewById(
R.id.nearby_devices_list_view);
if (nearbyDevicesListView != null) {
nearbyDevicesListView.setAdapter(mNearbyDevicesArrayAdapter);
}

Publish a message:

Publish the messages with nearby devices using nearby API

To publish a message, call Nearby.Messages.publish() passing your message byte array. We recommend keeping the messages to less than 3KB. Although these messages can deliver faster, but we can support up to 100KB for apps that needs it. This service is not meant for exchanging larger objects such as photos and videos. You can optionally call PublishOptions.setStrategy() to set the strategy to use.

The following example demonstrates calling publish() to send a small text message:

/**
* Publishes a message to nearby devices and updates the UI if the publication either fails or
* TTLs.
*/
private void publish() {
Log.i(TAG, "Publishing");
PublishOptions options = new PublishOptions.Builder()
.setStrategy(PUB_SUB_STRATEGY)
.setCallback(new PublishCallback() {
@Override
public void onExpired() {
super.onExpired();
Log.i(TAG, "No longer publishing");
runOnUiThread(new Runnable() {
@Override
public void run() {
mPublishSwitch.setChecked(false);
}
});
}
}).build();

Nearby.Messages.publish(mGoogleApiClient, mPubMessage, options)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Published successfully.");
} else {
logAndShowSnackbar("Could not publish, status = " + status);
mPublishSwitch.setChecked(false);
}
}
});
}
/**
* Stops publishing message to nearby devices.
*/
private void unpublish() {
Log.i(TAG, "Unpublishing.");
Nearby.Messages.unpublish(mGoogleApiClient, mPubMessage);
}

Subscribe the Message:

To subscribe to messages from other devices, call Nearby.Messages.subscribe(). You’ll need to pass a MessageListener to handle receiving subscribed, messages. You can optionally call SubscribeOptions. setStrategy () to set the strategy to use.

The following example demonstrates subscribing to messages:

/**
* Sets the time in seconds for a published message or a subscription to live. Set to three
* minutes in this sample.
*/
private static final Strategy PUB_SUB_STRATEGY = new Strategy.Builder()
.setTtlSeconds(TTL_IN_SECONDS).build();
/**
* Subscribes to messages from nearby devices and updates the UI if the subscription either
* fails or TTLs.
*/
private void subscribe() {
Log.i(TAG, "Subscribing");
mNearbyDevicesArrayAdapter.clear();
SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(PUB_SUB_STRATEGY)
.setCallback(new SubscribeCallback() {
@Override
public void onExpired() {
super.onExpired();
Log.i(TAG, "No longer subscribing");
runOnUiThread(new Runnable() {
@Override
public void run() {
mSubscribeSwitch.setChecked(false);
}
});
}
}).build();

Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Subscribed successfully.");
} else {
logAndShowSnackbar("Could not subscribe, status = " + status);
mSubscribeSwitch.setChecked(false);
}
}
});
}
/**
* Stops subscribing to messages from nearby devices.
*/
private void unsubscribe() {
Log.i(TAG, "Unsubscribing.");
Nearby.Messages.unsubscribe(mGoogleApiClient, mMessageListener);
}

Now, the nearby beacons would be encountered by a process that is running in the background and will get all the messages which we subscribe, publish and add them into the list of nearby messages.

You need to use the above subscribed, messages found in the nearby Beacons background and can get the all messages which are published using IntentService.

@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Nearby.Messages.handleIntent(intent, new MessageListener() {
@Override
public void onFound(Message message) {
Utils.saveFoundMessage(getApplicationContext(), message);
updateNotification();
}

@Override
public void onLost(Message message) {
Utils.removeLostMessage(getApplicationContext(), message);
updateNotification();
}
});
}
}

Then we need to change only one thing into call subscribe method :

if (mSubscribed) {
Log.i(TAG, "Already subscribed.");
return;
}

SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.build();

So, this is the NearBy Message API and Beacons which are saved and published via notification to you when you get on the proximity of the device or a beacon.

Hope this helps you kick start learning and R & D about the Beacons with NearBY API and performing an action on the Beacons with messages.

Thank You:)

Reference Sources:

https://www.youtube.com/watch?v=7InjJGqP15E

https://shakuro.com/blog/managing-beacons-in-android/

--

--

Sejal Baraiya
IndiaNIC

Software Quality Assurance Analyst and Android Developer | Always be ready for learning new things. It’s exciting….