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 Android phones detect the presence of each other. The device sear
Solution 1:
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// dialogNearby.Messages.getPermissionStatus(client)
.setResultCallback(newResultCallback<Status>() {
publicvoidonResult(Status status) {
// Request Nearby runtime permission if missing// ... see github sample for details// If you already have the Nearby permission,// call publishAndSubscribe()
}
});
voidpublishAndSubscribe() {
// 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 = newMessageListener() {
publicvoidonFound(Message msg) {
Log.i(TAG, "You found another device " + newString(msg));
}
});
Nearby.Messages.subscribe(googleApiClient, listener)
.setResultCallback(...);
}
Disclaimer I work on the Nearby API
Post a Comment for "Detecting Another Nearby Android Device Via Bluetooth"