How to create Bond or Pairing in BLE using RxAndroidBLE - android

I want to implement passkey for connect device or establish the connection with BLE device. I have 6 byte passkey, So how we will create bond or pairing and send passkey to the BLE device using RxAndroid library.
Can any one give me reference or document link or demo link for implementation of Passkey or create bond or pairing while establish connection.
Thanks in advance!!

First you need to find the nearby devices.
public void registerDeviceForAnyNEwDeviceFound() {
// Register for broadcasts when a device is discovered.
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mSearchReceiver, filter);
Log.e("STATUS", "" +
mBluetoothAdapter.isDiscovering());
isSearchReceiverRegistered = true;
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("SEARCH STARTED", "TRUE");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Device mDevice = new Device();
mDevice.setDeviceName(deviceName);
mDevice.setDeviceAddress(deviceHardwareAddress);
mDevice.setmBluetoothDevice(device);
Log.e("Discovered DEVICE", deviceName);
Log.e("BOND STATE", "" + device.getBondState());
nearbyDeviceList.add(mDevice);
mNearbyDeviceRecAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("EXCEPTION", e.getLocalizedMessage());
}
}
}
};
Then you need to register another BroadCastReceiver, this receiver will listen to the bond changes with the device with whom you are going to pair with.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairingReceiver, filter);
private final BroadcastReceiver mPairingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDED." + mDevice.getName());
mBluetoothAdapter.cancelDiscovery();
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDING." + mDevice.getName());
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
Log.e(TAG, "BroadcastReceiver: BOND_NONE." + mDevice.getName());
}
}
}
};
Finally when you want to pair with the device call:
mNearbyDeviceRecAdapter.getItemAtPosition(position).getmBluetoothDevice().createBond();
Once you call this statement, this will initiate pairing with the device.
Hope! this helps.

Related

Android Bluetooth - Getting NULL for UUID of bluetooth discovered devices

I want to share the data between 2 bluetooth devices without pairing and in both the phones my app will be installed
so i used this method (https://arxiv.org/ftp/arxiv/papers/1507/1507.00650.pdf)
Bluetooth device advertises a list of services using UUIDs numbers.
This how registered a service=====>
String uuid = "f2989d52-b3d6-4205-b34d-04f35ea264e5";
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket btSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("MYAPP", UUID.fromString(uuid))
Intents for callback===>
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter1);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_UUID);
registerReceiver(mReceiver, filter2);
After that i call
bluetoothAdapter.startDiscovery(); // to start discovery of devices
Code to handle intents==>
private final BroadcastReceiver mReceiver = new
BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("SUNIL","receiver");
String action = intent.getAction();
Log.e("SUNIL","receiver action"+action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Boolean uuid1 = device.fetchUuidsWithSdp();
mDeviceList.add(device);
Log.e("SUNIL","device uuid result"+uuid1);
Log.e("SUNIL","device"+device.getAddress()+device.getUuids()+device.getBondState());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// discovery has finished, give a call to fetchUuidsWithSdp on first device in list.
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
Log.e("SUNIL", "device uuid result223" + result+"==uuid finished"+device.getUuids());
}
}
else if (BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("SUNIL","device.getUuids()"+device.getUuids());
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuids != null) {
for (Parcelable ep : uuids) {
if (uuids != null) {
String uuid = ep.toString();
Log.e("SUNIL", "uuid===>" + uuid+"===="+device.getName());
**getting uuid null here**
}
}
}
}
}
};
Please help me and i am new to this bluetooth API's
I have trued with redmi 6A and redmi 6 PRO devices

Bluetooth device automatically disconnect

I don't know actually it is right platform to ask this question or not.
I am using the broadcast receiver to check whether the Bluetooth device is connected or not.
using following code.
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mBG5Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String bg5Tag="Bluetooth";
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("Device state",Integer.toString(device.getBondState()));
Log.i("Action is ",action);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
Log.d(bg5Tag,"Action connected");
Log.e("Device name ",device.getName());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
Log.d(bg5Tag,"Action searching");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
Log.d(bg5Tag,"Action about disconnect");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected
Log.d(bg5Tag,"Action disconnected");
Log.e("Device name ",device.getName());
}
else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
Log.d(bg5Tag,"Action pairing request");
Log.e("Device name ",device.getName());
}
}
};
But when I tap on the device to pair then device disconnected automatically. But it moved to paired devices list. Why it is disconnecting?

Android Cannot Detect Bluetooth Device

I am having a problem with my broadcast receiver and finding a particular device. Earlier in my program, I look for the current devices and allow the user to pick on. That name and address is saved off. When the application processes its "onResume", I create a broadcast receiver.
All I am attempting to do is see if the previously saved device is in the area. It doesn't have to be paired, but must at least be seen. I don't see any of these toast messages. I have even attempted to put the device into discover-able mode prior to this.
Here is my broadcast receiver.
mBluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Toast toast = Toast.makeText(getApplicationContext(), "BT Found", Toast.LENGTH_LONG);
toast.show();
if (deviceAddress.equals(mDeviceAddress)) {
Toast toasty = Toast.makeText(getApplicationContext(), "Correct BT Device Found", Toast.LENGTH_LONG);
toasty.show();
}
}
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Toast toast = Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_LONG);
toast.show();
if (deviceAddress.equals(mDeviceAddress)) {
Toast toasty = Toast.makeText(getApplicationContext(), "Correct BT Device Connected", Toast.LENGTH_LONG);
toasty.show();
}
}
} catch (Exception e) {
System.out.println("Broadcast Error : " + e.toString());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
this.registerReceiver(mBluetoothReceiver, filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mBluetoothReceiver, filter);
Edit
It seems that the connected and disconnection events are being detected properly. They are only detected on change. However, the ACTION_FOUND is not. I cannot simply be in the area of the device.

Second Android bluetooth connection fails on 00001105

I have written an application that regularly tries to connect to paired devices and, if the connection succeeds, performs an action. I have a registered bluetooth broadcastReceiver that handles ACTION_ACL_CONNECTED and ACTION_ACL_DISCONNECTED. In a service, in the run loop, I get the list of paired devices and attempt a connection to each. When the connection succeeds, I get the ACTION_ACL_CONNECTED notification and when the device disconnects (or goes out of range) I get the ACTION_ACL_DISCONNECTED. All works well.
For headsets, the BluetoothHeadset class raises ACTION_ACL_CONNECTED and ACTION_ACL_DISCONNECTED so I don't need to connect to a device whose primary UUID is 00001108.
I have a bluetooth speaker that has a single UUID of 0000110B. It can go in and out of range all day long and I get the ACTION_ACL_CONNECTED and ACTION_ACL_DISCONNECTED signals each time I connect to it and each time the disconnect happens because it goes out of range.
If I try to connect to another phone, using 00001105, the first connect succeeds and ACTION_ACL_CONNECTED is raised. If I take the phone out of range (or just turn off its bluetooth), I get ACTION_ACL_DISCONNECTED. However, any further connect attempt results in "Service discovery failed" even if the phone is in range and its bluetooth is on. This continues until i toggle the bluetooth adapter on my phone either manually or in code. Then I can do one connect/disconnect and then the Service discovery failure happens again. obviously, toggling the adapter is not a satisfactory solution.
So, my question is, what makes 00001105 different than 00001108 in that I cannot do multiple connect/disconnects with 00001105?
The code is relatively complex, but here it is (please excuse the indentation. Cut and paste didn't work very well):
public class BluetoothListenerService extends Service {
// The BroadcastReceiver that listens for Connected and disconnected blue tooth devices (HSP,HFP and SPP)
public final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String devices[]=null;
Intent service_intent;
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
String testUUID=null;
try {
Method method = device.getClass().getMethod("getUuids", (Class<?>[]) null);
ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(device, (Object[]) null);
UUID myUUID=phoneUuids[0].getUuid();
testUUID=myUUID.toString().toLowerCase();
Log.i(TAG,"connected to "+device.getName()+ "using "+ testUUID);
} catch (Exception e) {}
return;
} // end ACTION_ACL_CONNECTED
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.i(TAG, "disconnected from "+device.getName());
return;
} // end ACTION_ACL_DISCONNECTED
} // end OnReceive
}; // end broadcast receiver definition
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
public void onStart(final Intent intent, final int startId) {
super.onStart(intent, startId);
if (mBluetoothAdapter == null) {
Toast.makeText(this," Bluetooth is not available on this device", Toast.LENGTH_LONG).show();
return;
}
Thread t = new Thread("MyService(" + startId + ")") {
#Override
public void run() {
_onStart(intent, startId);
stopSelf();
}
};
t.start();
return;
}
public void _onStart(Intent intent, int startId) {
String devices[]=null;
Log.i(TAG,"Bluetooth Listener Service started on thread "+ Integer.toString(android.os.Process.myTid()));
// Register the Bluetooth BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
try {
this.unregisterReceiver(mBluetoothReceiver);
} catch(IllegalArgumentException ignorable) {}
registerReceiver(mBluetoothReceiver, filter);
// the loop
bRun=true;
while(bRun) {
Set <BluetoothDevice> mySet=mBluetoothAdapter.getBondedDevices();
Iterator <BluetoothDevice> iterator=mySet.iterator();
while(iterator.hasNext()) {
BluetoothDevice setElement=iterator.next();
String testUUID=null;
try { // Get UUID for device
Method method = setElement.getClass().getMethod("getUuids", (Class<?>[]) null);
ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(setElement, (Object[]) null);
UUID myUUID=phoneUuids[0].getUuid();
testUUID=myUUID.toString().toUpperCase();
Log.i(TAG, "device UUID is "+testUUID);
if (testUUID.compareTo(headsetUUID)!=0 && testUUID.compareTo(a2dpUUID)!=0) {
try { // create a socket
BluetoothSocket tmp=null;
tmp=setElement.createInsecureRfcommSocketToServiceRecord(UUID.fromString(testUUID));
mmSocket=tmp;
Log.i(TAG,"connecting using socket "+mmSocket.toString());
Log.i(TAG,"connecting to "+setElement.getName());
try {
if (mBluetoothAdapter.isDiscovering()==true) mBluetoothAdapter.cancelDiscovery();
mmSocket.connect();
Log.i(TAG,"connection to "+setElement.getName()+" was sucessful");
// the connection will be handled by the receiver in ACL_CONNECTED
} catch (Exception e) { // connection failed
String sTest=e.getMessage();
Log.e(TAG,"connection to "+setElement.getName()+" returned "+sTest);
if (sTest!=null) {
try { // closing the socket
Log.i(TAG,"closing socket due to error: "+sTest);
Log.i(TAG,"closing socket "+mmSocket.toString());
if (!mmSocket.equals(null)) {
mmSocket.close();
mmSocket=null;
tmp=null;
}
else {
Log.e(TAG, "socket is null");
}
} catch (Exception e1) { // socket close failed
Log.e(TAG,"closing socket failed");
break;
}
if (sTest.compareTo("Unable to start Service Discovery")==0) {
mBluetoothAdapter.disable();
SystemClock.sleep(3000);
mBluetoothAdapter.enable();
SystemClock.sleep(1000);
}
}
} // end catch connection failed
} catch (Exception e1) {
Log.e(TAG, "socket create failed.");
}
} // end test if headset or not
} catch (Exception e1) {
Log.e(TAG, "find UUID failed.");
} // end find UUID
} // end while iterator.hasnext()
} // end of run loop
}
}

Android Bluetooth: Get UUIDs of discovered devices

As I'm currently working on a little bluetooth library for Android, I'm trying to get all the service uuids of the devices I discovered in my surrounding.
When my broadcast receiver gets the BluetoothDevice.ACTION_FOUND intent, I'm extracting the device and call:
device.fetchUuidsWithSdp();
This will result BluetoothDevice.ACTION_UUID intents for each device found and I'm handling them with the same receiver:
BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuidExtra == null) {
Log.e(TAG, "UUID = null");
}
if(d != null && uuidExtra != null)
Log.d(TAG, d.getName() + ": " + uuidExtra.toString());
The thing is, that uuidExtra is always null.
How can i get all the UUIDs of the surrounding devices?
EDIT:
Im working on a Nexus 7. I tried code i found on the internet and this also gives me a NullPointerException: http://digitalhacksblog.blogspot.de/2012/05/android-example-bluetooth-discover-and.html
Thank you.
The documentation on this states...
Always contains the extra field BluetoothDevice.EXTRA_UUID
However, just like you, I have found this not to be true.
If you call fetchUuidsWithSdp() while device discovery is still taking place BluetoothDevice.EXTRA_UUID can be null.
You should wait until you receive BluetoothAdapter.ACTION_DISCOVERY_FINISHED before you make any calls to fetchUuidsWithSdp().
NOTE: This solution applies to CLASSIC bluetooth and not BLE. For BLE check how to send
manufacturer specific Data in advertiser on the peripheral side
The problem with fetching Uuids is that you have only one bluetooth adapter, and we cannot have parallel api calls which uses adapter for its purpose.
As Eddie pointed out, wait for BluetoothAdapter.ACTION_DISCOVERY_FINISHED and then call fetchUuidsWithSdp().
Still this cannot guarantee uuids to be fetched for all devices. In addition to this one must wait for each subsequent call to fetchuuidsWithSdp() to complete, and then give a call to this method for another device.
See the code below --
ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// discovery has finished, give a call to fetchUuidsWithSdp on first device in list.
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
}
} else if (BluetoothDevice.ACTION_UUID.equals(action)) {
// This is when we can be assured that fetchUuidsWithSdp has completed.
// So get the uuids and call fetchUuidsWithSdp on another device in list
BluetoothDevice deviceExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
System.out.println("DeviceExtra address - " + deviceExtra.getAddress());
if (uuidExtra != null) {
for (Parcelable p : uuidExtra) {
System.out.println("uuidExtra - " + p);
}
} else {
System.out.println("uuidExtra is still null");
}
if (!mDeviceList.isEmpty()) {
BluetoothDevice device = mDeviceList.remove(0);
boolean result = device.fetchUuidsWithSdp();
}
}
}
}
UPDATE: Latest android versions (mm & above) would result in triggering a pairing process with each device
Here is a good example of how to get UUIDs of service characteristics from a service that I did for getting heart rate devices:
private class HeartRateBluetoothGattCallback extends BluetoothGattCallback {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
logMessage("CONNECTED TO " + gatt.getDevice().getName(), false, false);
gatt.discoverServices();
} else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
logMessage("DISCONNECTED FROM " + gatt.getDevice().getName(), false, false);
if(mIsTrackingHeartRate)
handleHeartRateDeviceDisconnection(gatt);
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
logMessage("DISCOVERING SERVICES FOR " + gatt.getDevice().getName(), false, false);
if(mDesiredHeartRateDevice != null &&
gatt.getDevice().getAddress().equals(mDesiredHeartRateDevice.getBLEDeviceAddress())) {
if(subscribeToHeartRateGattServices(gatt)) {
mIsTrackingHeartRate = true;
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.CONNECTED);
broadcastHeartRateDeviceConnected(gatt.getDevice());
} else
broadcastHeartRateDeviceFailedConnection(gatt.getDevice());
} else {
parseGattServices(gatt);
disconnectGatt(getDiscoveredBLEDevice(gatt.getDevice().getAddress()));
}
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
if(characteristic.getUuid().equals(UUID.fromString(HEART_RATE_VALUE_CHAR_READ_ID))) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0)
format = BluetoothGattCharacteristic.FORMAT_UINT16;
else
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Integer heartRateValue = characteristic.getIntValue(format, 1);
if(heartRateValue != null)
broadcastHeartRateValue(heartRateValue);
else
Log.w(SERVICE_NAME, "UNABLE TO FORMAT HEART RATE DATA");
}
};
};
private void parseGattServices(BluetoothGatt gatt) {
boolean isHeartRate = false;
for(BluetoothGattService blueToothGattService : gatt.getServices()) {
logMessage("GATT SERVICE: " + blueToothGattService.getUuid().toString(), false, false);
if(blueToothGattService.getUuid().toString().contains(HEART_RATE_DEVICE_SERVICE_CHARACTERISTIC_PREFIX))
isHeartRate = true;
}
if(isHeartRate) {
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.IS_HEART_RATE);
broadcastHeartRateDeviceFound(getDiscoveredBLEDevice(gatt.getDevice().getAddress()));
} else
setDeviceScanned(getDiscoveredBLEDevice(gatt.getDevice().getAddress()), DiscoveredBLEDevice.NOT_HEART_RATE);
}
private void handleHeartRateDeviceDisconnection(BluetoothGatt gatt) {
broadcastHeartRateDeviceDisconnected(gatt.getDevice());
gatt.close();
clearoutHeartRateData();
scanForHeartRateDevices();
}
private void disconnectGatt(DiscoveredBLEDevice device) {
logMessage("CLOSING GATT FOR " + device.getBLEDeviceName(), false, false);
device.getBlueToothGatt().close();
device.setBlueToothGatt(null);
mInDiscoveryMode = false;
}
private boolean subscribeToHeartRateGattServices(BluetoothGatt gatt) {
for(BluetoothGattService blueToothGattService : gatt.getServices()) {
if(blueToothGattService.getUuid().toString().contains(HEART_RATE_DEVICE_SERVICE_CHARACTERISTIC_PREFIX)) {
mHeartRateGattService = blueToothGattService;
for(BluetoothGattCharacteristic characteristic : mHeartRateGattService.getCharacteristics()) {
logMessage("CHARACTERISTIC UUID = " + characteristic.getUuid().toString(), false, false);
for(BluetoothGattDescriptor descriptor :characteristic.getDescriptors()) {
logMessage("DESCRIPTOR UUID = " + descriptor.getUuid().toString(), false, false);
}
if(characteristic.getUuid().equals(UUID.fromString(HEART_RATE_VALUE_CHAR_READ_ID))) {
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(HEART_RATE_VALUE_CHAR_DESC_ID));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
}
break; //break out of master for-loop
}
}
return false;
}
I suppose you need to be paired with the device in order to receive the uuids.
At least, this is what happened to me.
device.getUuids() use this to get all the uuid of that paired device in the form of ParcelUuid; Example code below:-
private void get_uuid_from_paired_devices(){
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device: pairedDevices){
for (ParcelUuid uuid: device.getUuids()){
String uuid_string = uuid.toString();
Log.d(TAG, "uuid : "+uuid_string);
}
}
}
Below worked for me to fetch the records from the remote device
-0-
registerReceiver(..,
new IntentFilter(BluetoothDevice.ACTION_UUID));
-1-
device.fetchUuidsWithSdp();
-2-from within the broadcase receiver
if (BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (Parcelable ep : uuids) {
Utilities.print("UUID records : "+ ep.toString());
}
}
You can also fetch the offline cached UUID records with
BluetoothDevice.getUuids();

Categories

Resources