앱은 다른 근처 기기에서 게시한 메시지를 구독하는 데 사용되는 동일한 메커니즘을 사용하여 저전력 블루투스 (BLE) 비콘 첨부파일을 구독할 수 있습니다. 구독하면 앱이 비콘과 근처 기기 모두에서 메시지를 자동으로 수신합니다.
BLE 비콘 메시지 구독
There are two ways your app can subscribe to BLE beacon messages:
- In the foreground, in response to a user action or event.
- 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)
and setting the Strategy option to BLE_ONLY.
The following code snippet demonstrates initiating a foreground subscription
Nearby.getMessagesClient(Activity).subscribe(MessageListener, 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).
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.
Your app can initiate a background subscription by calling
Nearby.getMessagesClient(Activity).subscribe(PendingIntent, 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).
// 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).
Parse beacon messages
Beacon attachments are blobs of arbitrary data that you can add to beacons. 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.
프로젝트와 연결된 네임스페이스를 확인하려면 namespaces.list를 호출하세요.
참고:
-
배터리 수명을 보존하려면 활동의
onStop()함수에서Nearby.getMessagesClient(Activity).unsubscribe()을 호출하세요. 이는 포그라운드에서 구독하는 경우에만 적용됩니다. -
지연 시간을 줄이려면
Nearby.getMessagesClient(Activity).subscribe()을 호출할 때Strategy.BLE_ONLY옵션을 사용하세요. 이 옵션을 설정하면 Nearby Messages API가 기본 블루투스 검색을 트리거하지 않습니다. 이렇게 하면 시스템이 가능한 모든 스캔 유형을 순환하지 않으므로 비콘 감지 지연 시간이 개선됩니다. - 메시지 페이로드를 비콘에 연결하려면 근접 비콘 API를 사용하세요.