开发者

Detecting another nearby android device via Bluetooth

Alright, I've got a bit of a weird question here. I'm working on an Android game where I'd like to be able to have And开发者_开发问答roid phones detect the presence of each other.

The device searching for other players will know the bluetooth mac addresses of the other players' devices (from a game DB), however the devices will not be paired and the devices will not be in discoverable mode. Also, there will only be a handful of devices that could possibly be found - so it's not a big deal to scan through mac addresses.

I don't need to connect to the devices, I just need to be able to answer one simple question: is this device with this mac address nearby?

It is permissible to have a pairing dialog appear on the other user's screen...I don't care what the outcome of their choice is...I just need to know if their device is there.

Any help would be greatly appreciated!


This use-case may be a good fit for the recently released Nearby API. See the Nearby Messages developer overview

Nearby has its own runtime permission saving you from adding BLUETOOTH_ADMIN or similar to your manifest. It works across iOS and Android by utilizing multiple technologies (Classic Bluetooth, BLE, ultrasound). There's an option to use only the ultrasonic modem which reduces the range to about 5 feet.

I've included a partial example below, you can find a more complete sample on github

// Call this when the user clicks "find players" or similar
// In the ResultCallback you'll want to trigger the permission
// dialog
Nearby.Messages.getPermissionStatus(client)
  .setResultCallback(new ResultCallback<Status>() {
    public void onResult(Status status) {
      // Request Nearby runtime permission if missing
      // ... see github sample for details
      // If you already have the Nearby permission,
      // call publishAndSubscribe()
    }
  });

void publishAndSubscribe() {
  // You can put whatever you want in the message up to a modest
  // size limit (currently 100KB). Smaller will be faster, though.
  Message msg = "your device identifier/MAC/etc.".getBytes();
  Nearby.Messages.publish(googleApiClient, msg)
      .setResultCallback(...);

  MessageListener listener = new MessageListener() {
    public void onFound(Message msg) {
      Log.i(TAG, "You found another device " + new String(msg));
    }
  });

  Nearby.Messages.subscribe(googleApiClient, listener)
    .setResultCallback(...);
}

Disclaimer I work on the Nearby API

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜