Detecting another nearby android device via Bluetooth

后端 未结 1 1921
挽巷
挽巷 2021-02-04 20:05

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 Android phones detect the presence of each other.

T

相关标签:
1条回答
  • 2021-02-04 20:51

    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 讨论(0)
提交回复
热议问题