앱이 백그라운드에서 비콘 메시지를 구독하면 저전력 스캔을
화면 켜짐 이벤트 시 트리거되며 이는 앱이 현재 활성 상태가 아니어도 마찬가지입니다.
스캔 알림을 사용하여 '일어나기'를 할 수 있습니다. 앱에 대한 응답으로
확인할 수 있습니다. 백그라운드 구독은 배터리를 더 적게 소비합니다.
포그라운드 구독을 지원하지만 지연 시간이 길고 안정성이 낮습니다.
// Subscribe to messages in the background.privatevoidbackgroundSubscribe(){Log.i(TAG,"Subscribing for background updates.");SubscribeOptionsoptions=newSubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).build();Nearby.getMessagesClient(this).subscribe(getPendingIntent(),options);}privatePendingIntentgetPendingIntent(){returnPendingIntent.getBroadcast(this,0,newIntent(this,BeaconMessageReceiver.class),PendingIntent.FLAG_UPDATE_CURRENT);}
다음 코드 스니펫은
BeaconMessageReceiver 클래스.
@OverridepublicvoidonReceive(Contextcontext,Intentintent){Nearby.getMessagesClient(context).handleIntent(intent,newMessageListener(){@OverridepublicvoidonFound(Messagemessage){Log.i(TAG,"Found message via PendingIntent: "+message);}@OverridepublicvoidonLost(Messagemessage){Log.i(TAG,"Lost message via PendingIntent: "+message);}});}
비콘 첨부파일비콘에 추가할 수 있는 임의 데이터의 블롭입니다.
각 첨부파일은 다음과 같은 부분으로 구성됩니다.
네임스페이스: 네임스페이스 식별자입니다.
유형: 데이터 유형입니다.
데이터: 첨부파일의 데이터 값입니다.
다음 코드 스니펫은 메시지 리스너를 사용하여 파싱하는 방법을 보여줍니다.
메시지를 수신할 수 있습니다.
mMessageListener=newMessageListener(){@OverridepublicvoidonFound(Messagemessage){// Do something with the message here.Log.i(TAG,"Message found: "+message);Log.i(TAG,"Message string: "+newString(message.getContent()));Log.i(TAG,"Message namespaced type: "+message.getNamespace()+"/"+message.getType());}...};
콘텐츠 파싱은 바이트 형식에 따라 다릅니다. 이 예시에서는
콘텐츠 바이트는 UTF-8 문자열을 인코딩하지만 비콘 메시지는
다른 바이트 형식을 인코딩합니다 (예: 직렬화된 프로토콜 버퍼).
자세한 내용은 비콘에 첨부파일 추가를 참조하세요.
[null,null,["최종 업데이트: 2025-08-29(UTC)"],[[["\u003cp\u003eThe Google Beacon platform is deprecated and will shut down on April 1, 2021; however, you can still subscribe to Bluetooth Low Energy (BLE) beacon attachments using the Nearby Messages API.\u003c/p\u003e\n"],["\u003cp\u003eYour app can subscribe to BLE beacon messages in the foreground, continuously scanning while active, or in the background, triggering low-power scans at screen-on events.\u003c/p\u003e\n"],["\u003cp\u003eLocation services must be enabled on devices running Android 6.0 (Marshmallow) or higher to find messages attached to BLE beacons.\u003c/p\u003e\n"],["\u003cp\u003eBeacon attachments are customizable data blobs that include a namespace, type, and data value, which your app can parse to extract relevant information.\u003c/p\u003e\n"],["\u003cp\u003eTo optimize battery life and reduce latency, unsubscribe from foreground subscriptions in your Activity's onStop() function and utilize the Strategy.BLE_ONLY option when subscribing.\u003c/p\u003e\n"]]],["Apps can subscribe to Bluetooth Low Energy (BLE) beacon messages in the foreground or background. Foreground subscriptions use continuous scans initiated via `Nearby.getMessagesClient(Activity).subscribe(MessageListener, SubscribeOptions)` with `Strategy.BLE_ONLY`, requiring explicit unsubscription. Background subscriptions trigger low-power scans on screen-on events using `Nearby.getMessagesClient(Activity).subscribe(PendingIntent, SubscribeOptions)` with `Strategy.BLE_ONLY` requiring an unsubscribe method as well. Messages can be parsed for data and attachments using a `MessageListener`. The Google beacon platform is deprecated as of December 7, 2020, shutting down on April 1, 2021.\n"],null,["# Get Beacon Messages\n\n| **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.\n\nYour app can subscribe to Bluetooth Low Energy (BLE) [beacon attachments](/beacons/proximity/attachments)\nusing the same mechanism that is used to subscribe to messages published by\nother nearby devices. When subscribing, your app will automatically receive\nmessages from both beacons and nearby devices.\n| **Note:** Starting with Android 6.0 (Marshmallow), Location must be enabled to find messages attached to BLE beacons. Nearby does not automatically enable Location.\n| **Note:** In addition to beacon attachments, you can also subscribe to the raw [BLE beacon IDs](/nearby/messages/android/advanced#ble_beacon_ids).\n\nSubscribe to BLE beacon messages\n--------------------------------\n\nThere are two ways your app can subscribe to BLE beacon messages:\n\n- In the [foreground](#subscribe_in_the_foreground), in response to a user action or event.\n- In the [background](#subscribe_in_the_background), when your app is not running.\n\n### Subscribe in the foreground\n\nWhen your app subscribes to beacon messages in the foreground, scans are\nperformed continuously until your app unsubscribes. Only start a foreground\nsubscription when your app is active, typically in response to a user action.\n\nYour app can initiate a foreground subscription by calling\n[`Nearby.getMessagesClient(Activity).subscribe(MessageListener, SubscribeOptions)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#subscribe(com.google.android.gms.nearby.messages.MessageListener,%20com.google.android.gms.nearby.messages.SubscribeOptions))\nand setting the `Strategy` option to `BLE_ONLY`.\n\nThe following code snippet demonstrates initiating a foreground subscription\n[`Nearby.getMessagesClient(Activity).subscribe(MessageListener, SubscribeOptions)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#subscribe(com.google.android.gms.nearby.messages.MessageListener,%20com.google.android.gms.nearby.messages.SubscribeOptions)): \n\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ...\n mMessageListener = new MessageListener() {\n @Override\n public void onFound(Message message) {\n Log.d(TAG, \"Found message: \" + new String(message.getContent()));\n }\n\n @Override\n public void onLost(Message message) {\n Log.d(TAG, \"Lost sight of message: \" + new String(message.getContent()));\n }\n }\n }\n\n // Subscribe to receive messages.\n private void subscribe() {\n Log.i(TAG, \"Subscribing.\");\n SubscribeOptions options = new SubscribeOptions.Builder()\n .setStrategy(Strategy.BLE_ONLY)\n .build();\n Nearby.getMessagesClient(this).subscribe(mMessageListener, options);\n }\n\nWhen the subscription is no longer required, your app should unsubscribe\nby calling\n[`Nearby.getMessagesClient(Activity).unsubscribe(MessageListener)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#unsubscribe(com.google.android.gms.nearby.messages.MessageListener)).\n\n### Subscribe in the background\n\nWhen your app subscribes to beacon messages in the background, low-power scans\nare triggered at screen-on events, even when your app is not currently active.\nYou can use these scan notifications to \"wake up\" your app in response to a\nparticular message. Background subscriptions consumes less power than\nforeground subscriptions, but have higher latency and lower reliability.\n| **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.\n\nYour app can initiate a background subscription by calling\n[`Nearby.getMessagesClient(Activity).subscribe(PendingIntent, SubscribeOptions)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#subscribe(android.app.PendingIntent,%20com.google.android.gms.nearby.messages.SubscribeOptions))\nand setting the `Strategy` option to `BLE_ONLY`.\n\nThe following code snippet demonstrates initiating a background subscription by\ncalling\n[`Nearby.getMessagesClient(Activity).subscribe(PendingIntent, SubscribeOptions)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#subscribe(android.app.PendingIntent,%20com.google.android.gms.nearby.messages.SubscribeOptions)). \n\n // Subscribe to messages in the background.\n private void backgroundSubscribe() {\n Log.i(TAG, \"Subscribing for background updates.\");\n SubscribeOptions options = new SubscribeOptions.Builder()\n .setStrategy(Strategy.BLE_ONLY)\n .build();\n Nearby.getMessagesClient(this).subscribe(getPendingIntent(), options);\n }\n\n private PendingIntent getPendingIntent() {\n return PendingIntent.getBroadcast(this, 0, new Intent(this, BeaconMessageReceiver.class),\n PendingIntent.FLAG_UPDATE_CURRENT);\n }\n\nThe following code snippet demonstrates handling the intent in the\n`BeaconMessageReceiver` class. \n\n @Override\n public void onReceive(Context context, Intent intent) {\n Nearby.getMessagesClient(context).handleIntent(intent, new MessageListener() {\n @Override\n public void onFound(Message message) {\n Log.i(TAG, \"Found message via PendingIntent: \" + message);\n }\n\n @Override\n public void onLost(Message message) {\n Log.i(TAG, \"Lost message via PendingIntent: \" + message);\n }\n });\n }\n\nWhen the subscription is no longer required, your app should unsubscribe\nby calling\n[`Nearby.getMessagesClient(Activity).unsubscribe(PendingIntent)`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#unsubscribe(android.app.PendingIntent)).\n\nParse beacon messages\n---------------------\n\nBeacon [attachments](/beacons/proximity/reference/rest/v1beta1/beacons.attachments)\nare blobs of arbitrary data that you can [add to beacons](/beacons/proximity/attachments).\nEach attachment consists of the following parts:\n\n- Namespace: A namespace identifier.\n- Type: The data type.\n- Data: The data value for the attachment.\n\nThe following code snippet demonstrates using a message listener to parse\nmessages received from a BLE beacon: \n\n mMessageListener = new MessageListener() {\n @Override\n public void onFound(Message message) {\n // Do something with the message here.\n Log.i(TAG, \"Message found: \" + message);\n Log.i(TAG, \"Message string: \" + new String(message.getContent()));\n Log.i(TAG, \"Message namespaced type: \" + message.getNamespace() +\n \"/\" + message.getType());\n }\n\n ...\n };\n\nParsing the content depends on the format of the bytes. This example assumes\nthat the content bytes encode a UTF-8 string, but your beacon message can\nencode other byte formats (for example a serialized protocol buffer).\nFor more information, see [Add Attachments to Beacons](/beacons/proximity/attachments).\n\nTo find out which namespaces are associated with your project, call\n[namespaces.list](/beacons/proximity/reference/rest/v1beta1/namespaces/list).\n\nNotes:\n\n- To conserve battery life, call [`Nearby.getMessagesClient(Activity).unsubscribe()`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#unsubscribe(com.google.android.gms.nearby.messages.MessageListener)) in your Activity's `onStop()` function. Note that this applies only when subscribing in the [foreground](#subscribe_in_the_foreground).\n- To reduce latency, use the [`Strategy.BLE_ONLY`](/android/reference/com/google/android/gms/nearby/messages/Strategy#BLE_ONLY) option when calling [`Nearby.getMessagesClient(Activity).subscribe()`](/android/reference/com/google/android/gms/nearby/messages/MessagesClient#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.\n- To attach a message payload to a beacon, use the [Proximity Beacon API](/beacons/proximity/attachments).\n\n\u003cbr /\u003e"]]