> [!WARNING]
> **Warning:** The Google beacon platform is deprecated as of December 7, 2020. The platform will shut down on April 1, 2021. After this shut down, beacons will no longer be supported within the Nearby Messages API.

Your app can subscribe to Bluetooth Low Energy (BLE) [beacon attachments](https://developers.google.com/beacons/proximity/attachments)
using the same mechanism that is used to subscribe to messages published by
other nearby devices. When subscribing, your app will automatically receive
messages from both beacons and nearby devices.

> [!NOTE]
> **Note:** Starting with Android 6.0 (Marshmallow), Location must be enabled to find messages attached to BLE beacons. Nearby does not automatically enable Location.

> [!NOTE]
> **Note:** In addition to beacon attachments, you can also subscribe to the raw [BLE beacon IDs](https://developers.google.com/nearby/messages/android/advanced.md.txt#ble_beacon_ids).

## Subscribe to BLE beacon messages

There are two ways your app can subscribe to BLE beacon messages:

- In the [foreground](https://developers.google.com/nearby/messages/android/get-beacon-messages.md.txt#subscribe_in_the_foreground), in response to a user action or event.
- In the [background](https://developers.google.com/nearby/messages/android/get-beacon-messages.md.txt#subscribe_in_the_background), when your app is not running.

### Subscribe in the foreground

When your app subscribes to beacon messages in the foreground, scans are
performed continuously until your app unsubscribes. Only start a foreground
subscription when your app is active, typically in response to a user action.

Your app can initiate a foreground subscription by calling
[`Nearby.getMessagesClient(Activity).subscribe(MessageListener, SubscribeOptions)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#subscribe(com.google.android.gms.nearby.messages.MessageListener,%20com.google.android.gms.nearby.messages.SubscribeOptions))
and setting the `Strategy` option to `BLE_ONLY`.

The following code snippet demonstrates initiating a foreground subscription
[`Nearby.getMessagesClient(Activity).subscribe(MessageListener, SubscribeOptions)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#subscribe(com.google.android.gms.nearby.messages.MessageListener,%20com.google.android.gms.nearby.messages.SubscribeOptions)):

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        mMessageListener = new MessageListener() {
            @Override
            public void onFound(Message message) {
                Log.d(TAG, "Found message: " + new String(message.getContent()));
            }

            @Override
            public void onLost(Message message) {
                Log.d(TAG, "Lost sight of message: " + new String(message.getContent()));
            }
        }
    }

    // Subscribe to receive messages.
    private void subscribe() {
        Log.i(TAG, "Subscribing.");
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .build();
        Nearby.getMessagesClient(this).subscribe(mMessageListener, options);
    }

When the subscription is no longer required, your app should unsubscribe
by calling
[`Nearby.getMessagesClient(Activity).unsubscribe(MessageListener)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#unsubscribe(com.google.android.gms.nearby.messages.MessageListener)).

### Subscribe in the background

When your app subscribes to beacon messages in the background, low-power scans
are triggered at screen-on events, even when your app is not currently active.
You can use these scan notifications to "wake up" your app in response to a
particular message. Background subscriptions consumes less power than
foreground subscriptions, but have higher latency and lower reliability.

> [!NOTE]
> **Note:** Unlike a foreground subscription, Nearby does not automatically toggle the Bluetooth power state during a background subscription. Messages will not be found while Bluetooth is turned off.

Your app can initiate a background subscription by calling
[`Nearby.getMessagesClient(Activity).subscribe(PendingIntent, SubscribeOptions)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#subscribe(android.app.PendingIntent,%20com.google.android.gms.nearby.messages.SubscribeOptions))
and setting the `Strategy` option to `BLE_ONLY`.

The following code snippet demonstrates initiating a background subscription by
calling
[`Nearby.getMessagesClient(Activity).subscribe(PendingIntent, SubscribeOptions)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#subscribe(android.app.PendingIntent,%20com.google.android.gms.nearby.messages.SubscribeOptions)).

    // Subscribe to messages in the background.
    private void backgroundSubscribe() {
        Log.i(TAG, "Subscribing for background updates.");
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .build();
        Nearby.getMessagesClient(this).subscribe(getPendingIntent(), options);
    }

    private PendingIntent getPendingIntent() {
        return PendingIntent.getBroadcast(this, 0, new Intent(this, BeaconMessageReceiver.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
    }

The following code snippet demonstrates handling the intent in the
`BeaconMessageReceiver` class.

    @Override
    public void onReceive(Context context, Intent intent) {
        Nearby.getMessagesClient(context).handleIntent(intent, new MessageListener() {
            @Override
            public void onFound(Message message) {
                Log.i(TAG, "Found message via PendingIntent: " + message);
            }

            @Override
            public void onLost(Message message) {
                Log.i(TAG, "Lost message via PendingIntent: " + message);
            }
        });
    }

When the subscription is no longer required, your app should unsubscribe
by calling
[`Nearby.getMessagesClient(Activity).unsubscribe(PendingIntent)`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#unsubscribe(android.app.PendingIntent)).

## Parse beacon messages

Beacon [attachments](https://developers.google.com/beacons/proximity/reference/rest/v1beta1/beacons.attachments)
are blobs of arbitrary data that you can [add to beacons](https://developers.google.com/beacons/proximity/attachments).
Each attachment consists of the following parts:

- Namespace: A namespace identifier.
- Type: The data type.
- Data: The data value for the attachment.

The following code snippet demonstrates using a message listener to parse
messages received from a BLE beacon:

    mMessageListener = new MessageListener() {
        @Override
        public void onFound(Message message) {
            // Do something with the message here.
            Log.i(TAG, "Message found: " + message);
            Log.i(TAG, "Message string: " + new String(message.getContent()));
            Log.i(TAG, "Message namespaced type: " + message.getNamespace() +
                    "/" + message.getType());
        }

        ...
    };

Parsing the content depends on the format of the bytes. This example assumes
that the content bytes encode a UTF-8 string, but your beacon message can
encode other byte formats (for example a serialized protocol buffer).
For more information, see [Add Attachments to Beacons](https://developers.google.com/beacons/proximity/attachments).

To find out which namespaces are associated with your project, call
[namespaces.list](https://developers.google.com/beacons/proximity/reference/rest/v1beta1/namespaces/list).

Notes:

- To conserve battery life, call [`Nearby.getMessagesClient(Activity).unsubscribe()`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#unsubscribe(com.google.android.gms.nearby.messages.MessageListener)) in your Activity's `onStop()` function. Note that this applies only when subscribing in the [foreground](https://developers.google.com/nearby/messages/android/get-beacon-messages.md.txt#subscribe_in_the_foreground).
- To reduce latency, use the [`Strategy.BLE_ONLY`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/Strategy.md.txt#BLE_ONLY) option when calling [`Nearby.getMessagesClient(Activity).subscribe()`](https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessagesClient.md.txt#subscribe(com.google.android.gms.nearby.messages.MessageListener)). When this option is set, Nearby Messages API won't trigger classic Bluetooth scans. This improves the latency for beacon detection since the system doesn't cycle through all of the possible scan types.
- To attach a message payload to a beacon, use the [Proximity Beacon API](https://developers.google.com/beacons/proximity/attachments).

<br />